5

冒泡排序以及数组名相关内容

 1 year ago
source link: https://blog.51cto.com/u_15805387/5820712
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

冒泡排序以及数组名相关内容

精选 原创

ThereFY 2022-11-03 18:18:57 ©著作权

文章标签 数组名 数组 冒泡排序 文章分类 C/C++ 编程语言 阅读数249

void bubble_sort(int arr[], int sz)//冒泡排序
{
int i = 0;//确定冒泡排序的次数
for (i = 0; i < sz - 1; i++)
{
int flag = 1;//假设这一趟要排序的数据已经全部有序
//用来判断是否进入if语句,进入if语句说明还没排好序,需要继续排序
int j = 0;//每一趟冒泡排序
for (j = 0; j < sz - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
flag = 0;//本趟排序的数据其实不完全有序
}
}
if (flag == 1)//利用flag减少趟次数,提高效率
{
break;//if语句中不可以使用break语句,但此处break仍属于for循环中
}
}
}

#include<stdio.h>
int main()
{
int arr[] = {5,6,8,33,99,57 };
int i = 0;
int sz = sizeof(arr) / sizeof(arr[0]);//必须在外部求好,再移到函数中
bubble_sort(arr, sz);//冒泡排序函数
for (i = 0; i < sz; i++)
{
printf("%d ", arr[i]);
}
return 0;
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK