5.15
1 #include <iostream> 2 using namespace std; 3 template<class T> 4 void swapData(T& a, T& b) 5 { 6 T t = a; 7 a = b; 8 b = t; 9 } 10 11 template<class T> 12 void Bubblesort(T a[], int n) 13 { 14 int i = n - 1; 15 16 while (i > 0) 17 { 18 int lastExchangeIndex = 0; 19 for (int j = 0; j < i; j++) 20 if (a[j + 1] < a[j]) 21 { 22 swapData(a[j], a[j + 1]); 23 lastExchangeIndex = j; 24 } 25 i = lastExchangeIndex; 26 27 for (int k = 0;k < n;k++) 28 cout << a[k] << " "; 29 cout << endl; 30 } 31 } 32 33 int main() 34 { 35 int a[] = { 1,3,5,7,9,11,13,15,17,19,2,4,6,8,10,12,14,16,18,20 }; 36 37 cout << "排序前的数据:" << endl; 38 for (int i = 0; i < 20; i++) 39 cout << a[i] << " "; 40 cout << endl; 41 42 cout << "进行排序:" << endl; 43 Bubblesort(a, 20); 44 45 cout << "排序后的数据:" << endl; 46 for (int i = 0; i < 20; i++) 47 cout << a[i] << " "; 48 cout << endl; 49 50 return 0; 51 }