c语言冒泡排序怎样实现从大到小


本文摘自PHP中文网,作者coldplay.xixi,侵删。

c语言冒泡排序怎样实现从大到小

c语言冒泡排序的方法:

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

#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视频教程》

以上就是c语言冒泡排序怎样实现从大到小的详细内容!

相关阅读 >>

c语言冒泡排序怎样实现从大到小

c语言数组冒泡排序是如何实现的?

三分钟带你了解选择排序和冒泡排序的用法

更多相关阅读请进入《冒泡排序》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...