问题
冒泡排序(Bubble Sort),也称为沉降排序(Sinking Sort),之所以称其为冒泡排序,是因为算法中值相对较小的数据会像水中的气泡一样逐渐上升到数组的最顶端。与此同时,较大的数据逐渐地下沉到数组的底部。这个处理过程需在整个数组范围内反复执行多遍。每一遍执行时,比较相邻的两个元素。若顺序不对,则将其位置交换,当没有数据需要交换时,数据也就排好序了。
编程将排序函数DataSort()改用冒泡法实现。
输入格式要求:“%d” 提示信息:“Input n:” “Input %d numbers:”
输出格式要求:“Sorting results:” “%4d”
程序运行示例如下:
Input n:10
Input 10 numbers: 2 9 3 4 0 6 8 7 5 1
Sorting results: 0 1 2 3 4 5 6 7 8 9
#include <stdio.h>
#define N 10
int main()
{
int i, j,n, temp;
int a[N];
printf("Input n:");
scanf("%d", &n);
printf("Input %d numbers:", n);
for(i=0;i<n;i++)
{
scanf("%d", &a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j] > a[j+1])
{
temp= a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
printf("Sorting results:");
for(i=0;i<n;i++)
{
printf("%4d", a[i]);
}
return 0;
}