冒泡排序,前面幾個沒有排序

 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     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 };
29     int len = (int) sizeof(arrf) / sizeof(*arrf);
30     bubble_sort(arrf, len,3);
31     for (int i = 0; i < len; i++)
32         cout << arrf[i] << ' ';
33 
34     getchar();
35     return 0;
36 }

相關文章
相關標籤/搜索