温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

c语言实现冒泡排序

发布时间:2020-06-11 15:54:04 来源:亿速云 阅读:115 作者:鸽子 栏目:编程语言

c语言冒泡排序的方法:

先选定第一个数字为最大再对数字两两进行比较,得到两者之间的最大值,依次比较。具体代码实现如下:

#include <iostream>
#include <time.h>
using namespace std;
void srandData(int *, int );//产生随机数的函数
void bubbleSort(int *, int );//冒泡排序具体实现函数
void swap(int *, int *);//两个数字实现交换的函数
void display(int *, int );//在屏幕输出结果函数
int main()
{
const int N = 10;//定义常数
int arr[N];//定义数组
srandData(arr, N);
bubbleSort(arr, N);
display(arr, N);
return 0;
}
void srandData(int *a, int n)
{
srand(time(NULL));
for(int i = 0; i < n; i++)
{
a[i] = rand() % 50;//取50以下的数字
cout << a[i] << " ";
}
cout << endl;
}
void swap(int *b, int *c)
{
int temp = *c;
*c = *b;
*b = temp;
}
void bubbleSort(int *a, int n)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n - i - 1; j++)
{
if(a[j] < a[j + 1])
{
swap(&a[j], &a[j + 1]);//两者交换
}
}
}
}
void display(int *d, int n)
{
for(int i = 0; i < n; i++)
{
cout << d[i] << " ";
}
cout << endl;
}

以上就是c语言冒泡排序怎样实现从大到小的详细内容,更多请关注亿速云其它相关文章!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI