冒泡排序是一種簡單的排序演算法。 1 #pragma once 2 #include <iostream> 3 #include <assert.h> 4 using std::cout; 5 using std::endl; 6 template <typename T> void Swap(T & ...
冒泡排序是一種簡單的排序演算法。
1 #pragma once 2 #include <iostream> 3 #include <assert.h> 4 using std::cout; 5 using std::endl; 6 template <typename T> void Swap(T &a, T &b) 7 { 8 T temp = a; 9 a = b; 10 b = temp; 11 } 12 13 template <typename T> void Bubble(T a[], unsigned int n) 14 { 15 assert(sizeof(a) / sizeof(T) != n); 16 for (int k = 0; k < n; ++k) 17 cout << a[k] << "\t"; 18 cout << endl; 19 20 int loop = 0; 21 for (int i = 1; i < n - 1; ++i) 22 { 23 bool sorted = true; 24 cout << "第" << i << "次迴圈" << endl; 25 for (int j = 1; j < n; ++j) 26 { 27 if (a[j] < a[j - 1]) 28 { 29 Swap(a[j], a[j - 1]); 30 sorted = false; 31 } 32 for (int k = 0; k < n; ++k) 33 cout << a[k] << "\t"; 34 cout << endl; 35 loop++; 36 } 37 38 if (sorted) break; 39 } 40 cout << loop << endl; 41 } 42 43 44 int main() 45 { 46 double arr1[10] = { 1.2,3,1,9,6,4,5.9,7.1,8,8 }; 47 int len1 = sizeof(arr1)/sizeof(double); 48 Bubble(arr1, len1); 49 50 int arr2[10] = { 1,3,1,9,6,4,5,7,8,8 }; 51 int len2 = sizeof(arr2) / sizeof(int); 52 Bubble(arr2, len2); 53 54 system("pause"); 55 return 0; 56 }