《数据结构与算法分析——c语言描述》 练习7.14 答案
直接从相邻2个,4个,8个……排序,要注意的最后的结尾如何处理
#include<stdlib.h> #include<stdio.h> #include"fatal.h" int RandInt(int i, int j) { int temp; temp = (int)(i + (1.0*rand() / RAND_MAX)*(j - i)); return temp; } void getRandomInt(int *A, int n) { for (int i = 0; i < n; i++) { A[i] = i + 1; } for (int i = 1; i < n; i++) { //std::swap(A[i], A[RandInt(0, i)]); int randAdrr = RandInt(0, i); int t = A[i]; A[i] = A[randAdrr]; A[randAdrr] = t; } } int a[99999999]; void merge(int a[], int tempArray[], int left, int right, int rightEnd) { int i, j, k; int leftEnd; for (i = left, j = right, k = left, leftEnd = right - 1; i <= leftEnd && j <= rightEnd; k++) { if (a[i] < a[j]) { tempArray[k] = a[i]; i++; } else { tempArray[k] = a[j]; j++; } } while (i <= leftEnd) { tempArray[k++] = a[i++]; } while (j <= rightEnd) { tempArray[k++] = a[j++]; } for (int i = left; i <= rightEnd; i++) a[i] = tempArray[i]; } void mSort(int a[], int tempArray[], int left, int right) { if (left < right) { int center = (left + right) / 2; mSort(a, tempArray, left, center); mSort(a, tempArray, center + 1, right); merge(a, tempArray, left, center + 1, right); } } void mergeSort(int a[], int n) { int *tempArray = malloc(sizeof(int)*n); if (tempArray == NULL) Error("OUT OF MEMORY"); //mSort(a, tempArray, 0, n - 1); for (int len = 1; len < n; len *= 2) { for (int beg_pos = 0; beg_pos < n; beg_pos += (2 * len)) { { int i, j, k; int leftEnd, rightEnd; for (i = beg_pos, j = beg_pos + len, k = beg_pos, leftEnd = min(j - 1, n - 1), rightEnd = min(j + len - 1, n - 1); i <= leftEnd && j <= rightEnd; k++) { if (a[i] < a[j]) { tempArray[k] = a[i]; i++; } else { tempArray[k] = a[j]; j++; } } while (i <= leftEnd) { tempArray[k++] = a[i++]; } while (j <= rightEnd) { tempArray[k++] = a[j++]; } for (int i = beg_pos; i <= rightEnd; i++) a[i] = tempArray[i]; } } } free(tempArray); } #define N 2222 int main() { getRandomInt(a, N); mergeSort(a, N); int cnt = 1; for (int i = 0; i < N; i++) if (cnt == a[i]) cnt++; else Error("error"); }