#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<malloc.h> void MergeSortNonR(int* a, int n) { int* tmp = (int*)malloc(sizeof(int)*n); int gap = 1; // 每组数据个数 while (gap < n) { for (int i = 0; i < n; i += 2 * gap) { // [i, i+gap-1] [i+gap,i+2*gap-1] int begin1 = i, end1 = i + gap - 1; int begin2 = i + gap, end2 = i + 2 * gap - 1; // 归并过程中右半区间可能就不存在 if (begin2 >= n) break; // 归并过程中右半区间算多了, 修正一下 if (end2 >= n) { end2 = n - 1; } int index = i; while (begin1 <= end1 && begin2 <= end2) { if (a[begin1] < a[begin2]) { tmp[index++] = a[begin1++]; } else { tmp[index++] = a[begin2++]; } } while (begin1 <= end1) { tmp[index++] = a[begin1++]; } while (begin2 <= end2) { tmp[index++] = a[begin2++]; } // 拷贝回去 for (int j = i; j <= end2; ++j) { a[j] = tmp[j]; } } gap *= 2; } free(tmp); } int main() { int a[10] = { 3, 7, 8, 1, 4, 0, 5, 6, 2, 9 }; int n = sizeof(a) / sizeof(int); MergeSortNonR(a, n); for (int i = 0; i < n; i++) { printf("%d ",a[i]); } return 0; }
该算法最重要的步骤就是界限的设置