1 /*
2 冒泡排序: 效率很低,速度慢...不适合大量数据排序
3
4 原理:从左向右扫描数据,选择交大的数据,放在右边,进行交换
5 关于i和j的说明
6 */
7 #include "Bubble.h"
8 #include <stdio.h>
9 #include <iostream>
10 using namespace std;
11
12 void BubbleSort(int list[],int n);
13 void PrintArray(int list[],int n);
14 void BubbleSortBigToSmall(int list[],int n);
15 int main()
16 {
17
18 const int nLen=10;
19 int list[nLen] = {1,3,5,7,9,2,4,6,8,0};
20
21
22 //从小到大排序
23 cout<<"交换前的数据: ";
24 PrintArray(list,nLen);
25 BubbleSort(list,nLen);
26 cout<<"\n交换后的数据: ";
27 PrintArray(list,nLen);
28
29
30
31 //从大到小排序
32 cout<<"\n交换后的数据: ";
33 BubbleSortBigToSmall(list,nLen);
34 PrintArray(list,nLen);
35
36
37 cout<<"\nhello world"<<endl;
38 system("pause");
39 return 0;
40 }
41
42
43 //从小到大排序
44 void BubbleSort(int list[],int n)
45 {
46
47 for (int i=0;i<n-1;i++)
48 {
49 for (int j=0;j<n-1-i;j++)
50 {
51 if (list[j] > list[j+1]) // 比较运算符决定 从大到小,还是从小到大排序
52 {
53 std::swap(list[j],list[j+1]); //这个swap()是c++自带的交换函数
54 }
55 }
56 }
57
58 return ;
59 }
60
61
62 //从大到小排序
63 void BubbleSortBigToSmall(int list[],int n)
64 {
65
66 for (int i=0;i<n-1;i++)
67 {
68 for (int j=0;j<n-1-i;j++)
69 {
70 if (list[j] < list[j+1])
71 {
72 std::swap(list[j],list[j+1]);
73 }
74 }
75 }
76
77 return ;
78 }
79
80 //打印数组元素
81 void PrintArray(int list[],int n)
82 {
83
84 for (int i=0;i<n;i++)
85 {
86 cout<<list[i]<<" ";
87 }
88
89 return;
90 }
91
92
93 //获取数组的长度 这个留着以后来补充,暂时不知道怎么计算数组的长度
94 int GetArrayLen(int list[])
95 {
96 int nSize=0;
97
98 while (true)
99 {
100 //通过异常来捕获越界
101
102 nSize++;
103 }
104
105
106 return nSize;
107 }
108
109
110 //找出数组中的最大数
111 int GetMax(int list[],int nLen)
112 {
113
114 int temp=0;
115 for (int i=0;i<nLen;i++)
116 {
117 if (list[i] > temp)
118 {
119 temp = list[i];
120 }
121 }
122
123 printf("\ntemp=%d\n",temp);
124
125 return temp;
126 }