#include<iostream> using namespace std; 归并排序任何情况下: O(nlog2n)空间复杂度O(n) 稳定的排序算法(外排采用) */ void merge(int a[], int start, int mid, int end){ int i = start; int j = mid + 1; int k = 0; int *temp = new int[end - start + 1]; while (i <= mid && j <= end){ if (a[i] < a[j]){ temp[k++] = a[i++]; } else{ temp[k++] = a[j++]; } } if (i <= mid){ while (i <= mid){ temp[k++] = a[i++]; } } else{ while (j <= end){ temp[k++] = a[j++]; } } for (i = start,k=0; i <= end; i++,k++){ a[i] = temp[k]; } delete []temp; } void mergeSort(int arr[], int low, int high) { if (low<high) { int mid = (low + high) / 2; mergeSort(arr, low, mid); mergeSort(arr, mid + 1, high); merge(arr, low, mid, high); } } void print(int a[], int n){ for (int i = 0; i < n; i++){ cout << a[i] << " "; } cout << endl; } void main(){ int a[] = { 3, 112, 0, 12, 90, 23 }; int n = sizeof(a) / sizeof(a[0]); cout << "排序前:" << endl; print(a, n); mergeSort(a, 0, n - 1); cout << "排序后:" << endl; print(a, n); system("pause"); }
|