冒泡排序的实现原理很简单
1. 右边的数值大于左边,则进行交换
2. 每次遍历一定会确定一个最大值
3. 对于长度为n的数组,只需要进行(n-1)次遍历
实现代码
#include <stdio.h>
void bubble_sort(int a[], int n)
{
int i, j, temp;
for (j = 0; j < n - 1; j++)//对于长度为n的数组,只需要遍历n-1次
{
for (i = 0; i < n - 1 -j ; i++)//因为每次遍历一定会确定一个最大值,所以-j,保证后面的不必再次进行比较
{
if(a[i] > a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
}
}
int main()
{
int number[8] = {95, 45, 15, 78, 84, 51, 24, 12};
int i;
bubble_sort(number, 8);
for (i = 0; i < 8; i++)
{
printf("%d
", number[i]);
}
return 0;
}
