基於陣列的歸併排序--遞迴法(C++/C)
阿新 • • 發佈:2018-12-10
void mergeTwoArray(int *a, int left, int mid, int right, int *temp) { int i = left; int j = mid + 1; int t = 0; while (i <= mid && j <= right) { if (a[i] <= a[j]) temp[t++] = a[i++]; else temp[t++] = a[j++]; } while (i <= mid) temp[t++] = a[i++]; while (j <= right) temp[t++] = a[j++]; t = 0; while (left <= right) a[left++] = temp[t++]; } void sortArray(int *a, int left, int right, int *temp) { if (left < right) { int mid = left + (right - left) / 2; sortArray(a, left, mid, temp); sortArray(a, mid + 1, right, temp); mergeTwoArray(a, left, mid, right, temp); } } int main() { int a[] = { 4,5,7,2,3,1,9,0 }; int len = sizeof(a) / sizeof(int); int *temp = (int *)malloc(sizeof(int)*len); sortArray(a, 0, len - 1, temp); for (int i = 0; i < len; i++) cout << a[i] << '\t' << endl; return 0; }