1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
| #include <iostream> #include <string> using namespace std; int *b;
void Merge(int arr[], int low, int mid, int high) { int i, j, k; for (k = low; k <= high; k++) { b[k] = arr[k]; } for (i = low, j = mid + 1, k = i; i <= mid && j <= high; k++) { if (b[i] <= b[j]) { arr[k] = b[i++]; }else { arr[k] = b[j++]; } } while (i <= mid) { arr[k++] = b[i++]; } while (j <= high) { arr[k++] = b[j++]; } }
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 PrintArray(int arr[], int n) { for (int i = 0; i < n; i++) { cout << arr[i] << " "; } printf("\n"); } int main() { int arr[] = {12, 28, 20, 50, 48, 1, 5, 28}; int n = sizeof(arr) / sizeof(arr[0]); b = (int *)malloc(n * sizeof(int)); cout << "输出arr初始数组" << endl; PrintArray(arr, n); cout << "arr堆排序" << endl; MergeSort(arr,0, n - 1 ); cout << "输出arr排序后数组" << endl; PrintArray(arr, n); return 0; }
|