冒泡排序
//e.g.设计一个函数实现冒泡排序,将一个整型数组排序
void Bubble_Sort(int* arr, int sz)
//arr是数组,对数组传参,传的是首元素地址&arr[0]
{
//确定bubble排序的趟数
int i = 0;
int count = 0;
for (i = 0; i < sz - 1; i++)
{
int flag = 1;
int j = 0;
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = 0;
//本趟排序的数据不完全有序,进行交换
count++;
}
}
if (flag == 1)//有序,跳出循环,冒泡结束
break;
}
printf("共排序%d次\n", count);
}
int main()
{
//int arr[] = { 9,8,7,6,4,5,3,2,1 };//36
int arr[] = { 1,2,3,4,5,6,7,8,9 };//36
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);
//对数组进行升序排序
Bubble_Sort(arr, sz);
for (i = 0; i < sz; i++)
printf("%d ", arr[i]);
printf("\12");
return 0;
}
标签:sz,arr,int,冒泡排序,++,排序
From: https://blog.51cto.com/u_16287559/9393996