参考代码如下: #include <iostream> #include <assert.h> #include <algorithm> #include <string> using namespace std; int a[20] = {0}; int b[] = {5,3,6,1,8,4,4,19,11,33,2,80,76,7,13,22,87,11,35,1,26,14,21,45,70,28}; void init() { memset(a,0,sizeof(a)); for (int i = 0; i < sizeof(a) / sizeof(int); ++i) { a[i] = b[i]; } } void print_array() { cout<<"----------------------------------------------------------------------"<<endl; for (int i = 0; i < sizeof(a) / sizeof(int); ++i) { cout<<a[i]<<" "; } cout<<endl; } void bubble_sort() { int exchange = sizeof(a) / sizeof(int) - 1; while (exchange != -1) { int n = exchange; exchange = -1; for (int i = 0; i < n; ++i) { if (a[i] > a[i+1]) { exchange = i; swap(a[i],a[i+1]); } } } } void insert_sort() { int n = sizeof(a) / sizeof(int), i = 0, j = 0; int temp = a[0]; for (i = 1; i < n ; ++i) { temp = a[i]; for (j = i - 1; j >= 0; --j) { if (temp < a[j]) { a[j+1] = a[j]; } else break; } a[j+1] = temp; } } int quick_sort_partition(int a1[], int begin, int end) { int pivot = a1[begin], i = begin, j = end; while (i < j) { while (i < j && pivot <= a[j]) j--; if (i < j) a[i++] = a[j]; while ( i < j && pivot >= a[i]) i++; if (i < j) a[j--] = a[i]; } a[i] = pivot; return i; } void quick_sort(int a1[], int begin, int end) { if (begin >= end) return; int q = quick_sort_partition(a1, begin, end); quick_sort(a1, begin, q - 1); quick_sort(a1, q + 1, end); } void merge_sort_merge(int a1[], int begin, int mid, int end) { int a2[21] = {0}, a3[21] = {0}; int size_a2 = mid - begin + 1, size_a3 = end - mid; for (int i = 0; i < size_a2; ++i) { a2[i] = a1[begin + i]; } a2[size_a2] = 100000; for (int i = 0; i < size_a3; ++i) { a3[i] = a[mid + i + 1]; } a3[size_a3] = 100000; int i = begin, j2 = 0, j3 = 0; while (j2 < size_a2 && j3 < size_a3) { if (a2[j2] <= a3[j3]) a1[i++] = a2[j2++]; else a1[i++] = a3[j3++]; } while (j2 < size_a2) a1[i++] = a2[j2++]; while (j3 < size_a3) a1[i++] = a3[j3++]; assert(i == end + 1); } void merge_sort(int a1[], int begin, int end) { if (begin >= end) return; int mid = (begin + end) / 2; merge_sort(a1, begin, mid); merge_sort(a1, mid + 1, end); merge_sort_merge(a1,begin,mid,end); } void keep_heap(int a1[], int i, int heapsize) { int maxindex = i; int maxdata = a[i]; if (i * 2 < heapsize && a[i*2] > a[i]) { maxindex = i * 2; maxdata = a[i*2]; } if (i * 2 + 1 < heapsize && a[i*2+1] > maxdata) { maxindex = i * 2 + 1; } if (i != maxindex) { swap(a[i],a[maxindex]); keep_heap(a1, maxindex, heapsize); } } void make_heap(int a1[], int heapsize) { for (int i = heapsize / 2; i >= 0; --i) { keep_heap(a1,i,heapsize); } } void heap_sort(int a1[], int heapsize) { make_heap(a1,heapsize); for (int i = heapsize; i > 0; --i) { swap(a1[0],a1[heapsize-1]); heapsize--; keep_heap(a1,0,heapsize); } } int main() { init(); print_array(); //bubble_sort(); //insert_sort(); //quick_sort(a,0,sizeof(a) / sizeof(int) - 1); //merge_sort(a,0,sizeof(a) / sizeof(int) - 1); heap_sort(a,sizeof(a) / sizeof(int)); print_array(); return 0; }