冒泡排序算法
1 #include<iostream> 2 #include<iomanip> 3 #include<ctime> 4 using namespace std; 5 const int arrSize = 8; 6 7 void getArray(int a[], int n) // 产生数组 8 { 9 int i = 0; 10 srand(time(0)); // 根据系统时间设置随机数种子,有这个数以后才可以产生随机数 11 for (int i=0; i < n; i++) 12 a[i] = rand()%100; // 产生n个100以内的随机数 13 } 14 void showArray(int a[], int n) // 输出数组元素 15 { 16 for (int i = 0; i < n; i++) 17 cout << setw(5) << a[i]; 18 cout << endl; 19 } 20 void bubbleSort(int a[], int n) // 冒泡排序算法 21 { 22 int i, j, t; 23 for(i=0;i<n-1;i++) // 循环n-1趟 24 for(j=0;j<n-1-i;j++) // 每趟比较n-1-i次 25 if (a[j] > a[j + 1]) // 如果满足条件,则进行交换 26 { 27 t = a[j]; 28 a[j] = a[j + 1]; 29 a[j + 1] = t; 30 } 31 } 32 int main() 33 { 34 int values[arrSize]; 35 getArray(values, arrSize); // 产生数组 36 cout << "排序前:\n"; 37 showArray(values, arrSize); // 输出数组元素 38 bubbleSort(values, arrSize); // 冒泡排序算法 39 cout << "排序后:\n"; 40 showArray(values, arrSize); // 输出排序后的数组元素 41 return 0; 42 }