冒泡排序,前面还有印象吗?
#include <stdio.h>
int main(){
int a[] = {1,2,4,3,8,5};
//数组总共有多少元素
int n = (sizeof a)/(sizeof (int));
//定义一个中间变量用于交换数据
int t = 0;
for (int i = 0;i<n-1;i++){//要进行n-1轮排序(从i=0到i=n-2,i=0,1,2,3,4)
for (int j = 0;j<n-i-1;j++){
if (a[j]<a[j+1]){
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
for (int k = 0;k<n;k++)
{
printf("%d\t",a[k]);
}
return 0;
}
|
|