#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
int main()
{
int score[] = {1, 2, 3, 4, 5, 7, 6};
printf("before sort: ");
for(int i=0;i < 7;i++)
{
printf("%d ", score[i]);
}
int sortTimes = BubbleSort(score, 7);
printf("\nafter sort: ");
for(int i=0;i < 7;i++)
{
printf("%d ", score[i]);
}
printf("\nsortTimes: %d", sortTimes);
return 0;
}
int BubbleSort(int score[], int n)
{
int sortTimes=0,temp;
bool sorted = false;
for(int i=0;i < n-1;i++)
{
sorted = false;
for(int j=0;j < n-i-1;j++)
{
if(score[j] > score[j+1])
{
temp = score[j+1];
score[j+1] = score[j];
score[j] = temp;
sortTimes++;
sorted = true;
}
}
if(!sorted)
break;
}
return sortTimes;
}
注:
- C99中没有特定的布尔类型,因此引入<stdbool.h>使用bool类型
- 当在一遍二层循环中没有发生交换时,说明排序已经完成,直接结束循环