冒泡排序,前面几个没有排序
1 #include "stdafx.h" 2 #include <iostream> 3 using namespace std; 4 template<typename T> 5 //整数或浮点数皆可使用 6 void bubble_sort(T arr[], int len,int index=0) 7 { 8 int i, j; T temp; 9 for (i = 0; i < len - 1; i++) 10 for (j = index; j < len - 1 - i; j++) 11 if (arr[j] < arr[j + 1]) 12 { 13 temp = arr[j]; 14 arr[j] = arr[j + 1]; 15 arr[j + 1] = temp; 16 } 17 } 18 int main() 19 { 20 int arr[] = { 61, 17, 29, 22, 34, 60, 72, 21, 50, 1, 62 }; 21 int len = (int) sizeof(arr) / sizeof(*arr); 22 bubble_sort(arr, len); 23 for (int i = 0; i < len; i++) 24 cout << arr[i] << ' '; 25 26 cout << endl; 27 28