基本思想
归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
代码实现
#include<iostream> using namespace std; void MergeArray(int Array[], int First, int Middle, int Last, int P[]) { int i = First, j = Middle + 1; int m = Middle, n = Last; int k = 0; while (i <= m&&j <= n) { if (Array[i] <= Array[j]) { P[k] = Array[i]; ++k; ++i; } else { P[k] = Array[j]; ++k; ++j; } } while (i <= m)//若后一个表被取空 { P[k] = Array[i]; ++k; ++i; } while (j <= n)//若前一个表被取空 { P[k] = Array[j]; ++k; ++j; } for (int i = 0; i <k; i++) { Array[First + i] = P[i]; } } void MergeSort(int Array[], int First, int Last, int P[]) { if (First < Last) { int mid = (First + Last) / 2; MergeSort(Array, First, mid, P); MergeSort(Array, mid + 1, Last, P); MergeArray(Array, First, mid, Last, P); } } int main() { int MyData[10] = { 12,13,16,22,9,14,15,20,23,24 }; int *Result = new int[10];//存储排序结果 MergeSort(MyData, 0, 9, Result); delete[] Result; for (int i = 0; i < 10; i++) { cout << MyData[i] << " "; } cout << endl; system("pause"); return 0; }
时间: 2024-10-15 05:11:18