C++ 一起来回忆“冒泡排序”
例1,输出最大值
1 #include <iostream>
2 #include <iomanip>
3 using namespace std;
4 int main(void)
5 {
6 int a[2][3] = { { 15,34,23 },{ 54,27,65 } }; // 二维数组
7 int i, j, k;
8 int row, col;
9 int max = 0;
10 for (i = 0; i <= 1; i++)
11 for (j = 0; j <= 2; j++)
12 {
13 cout << setw(4) << a[i][j];
14 if (j == 2)
15 cout << endl;
16 }
17 cout << " *********************** " << endl;
18 for (i = 0; i <= 1; i++)
19 for (j = 0; j <= 2; j++)
20 {
21 if (max < a[i][j]) {
22 max = a[i][j];
23 row = i+1;
24 col = j+1;
25 }
26 }
27 cout << "The bigger number is:" << max << endl;
28 cout << "row=" << row << "," << "col=" << col << endl;
29 return 0;
30 }
结果:
15 34 23
54 27 65
***********************
The bigger number is:65
row=2,col=3
------------------------------------------------------------------------------------
例2,大小排序(https://baike.baidu.com/item/冒泡排序/4602306?fr=aladdin)
1 #include <iostream> 2 using namespace std; 3 template<typename T> 4 //整数或浮点数皆可使用 5 void bubble_sort(T arr[], int len) 6 { 7 int i, j; T temp; 8 for (i = 0; i < len - 1; i++) 9 for (j = 0; j < len - 1 - i; j++) 10 if (arr[j] > arr[j + 1]) 11 { 12 temp = arr[j]; 13 arr[j] = arr[j + 1]; 14 arr[j + 1] = temp; 15 } 16 } 17 int main() 18 { 19 int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 }; 20 int len = (int) sizeof(arr) / sizeof(*arr); 21 bubble_sort(arr, len); 22 for (int i = 0; i < len; i++) 23 cout << arr[i] << ' '; 24 25 cout << endl; 26 27 float arrf[] = { 17.5, 19.1, 0.6, 1.9, 10.5, 12.4, 3.8, 19.7, 1.5, 25.4, 28.6, 4.4, 23.8, 5.4 }; 28 len = (int) sizeof(arrf) / sizeof(*arrf); 29 bubble_sort(arrf, len); 30 for (int i = 0; i < len; i++) 31 cout << arrf[i] << ' '; 32 33 return 0; 34 }
本文来自博客园,作者:꧁执笔小白꧂,转载请注明原文链接:https://www.cnblogs.com/qq2806933146xiaobai/p/12228733.html