手写归并排序算法

2021/7/21 21:06:11 浏览：

• 二分法，切分成2个子数组；
• 递归对2个子数组进行归并排序；
• 将2个排好序的子数组，合并为1个有序数组。

``````void merge_sort(int* parr, int left, int right) {  // both left and right are inclusive
if (left >= right) return;

int mid = (left + right) / 2;
merge_sort(parr, left, mid);
merge_sort(parr, mid + 1, right);
merge_sub_array(parr, left, mid, right);
}``````

``````static void merge_sub_array(int* parr, int left, int mid, int right) {
int cnt = right - left + 1;
int* pnew = (int*)malloc(cnt * sizeof(int));
int nidx = 0;

int lidx = left, ridx = mid + 1;
while ((lidx <= mid) && (ridx <= right)) {
pnew[nidx++] = (parr[lidx] <= parr[ridx]) ? parr[lidx++] : parr[ridx++];
}

while (lidx <= mid) {
pnew[nidx++] = parr[lidx++];
}

while (ridx <= right) {
pnew[nidx++] = parr[ridx++];
}

memcpy(parr + left, pnew, cnt*sizeof(int));
free(pnew);
}``````

``````static void merge_sub_array(int* parr, int left, int mid, int right) {
int lidx = left, ridx = mid + 1;
while ((lidx <= mid) && (ridx <= right)) {
if (parr[lidx] <= parr[ridx]) {
lidx++;
} else {
int val = parr[ridx];
memmove(parr + lidx + 1, parr + lidx, (ridx - lidx) * sizeof(int));
parr[lidx++] = val;
mid++;
ridx++;
}
}
}``````

​我的微信号是 实力程序员，欢迎大家转发至朋友圈，分享给更多的朋友。