归并排序c语言diedai
时间: 2023-11-12 22:58:13 浏览: 144
归并排序 (c语言版)
归并排序的迭代实现可以使用循环和队列来实现。具体实现步骤如下:
1. 将待排序数组分成若干个长度为1的子数组;
2. 依次将相邻的两个子数组合并成一个有序的大数组,直到所有子数组都被合并成一个有序的数组。
以下是归并排序的迭代实现代码:
```c
void merge_sort_iter(int arr[], int len) {
int* a = arr;
int* b = (int*) malloc(len * sizeof(int));
int seg, start;
for (seg = 1; seg < len; seg += seg) {
for (start = 0; start < len; start += seg + seg) {
int low = start, mid = min(start + seg, len), high = min(start + seg + seg, len);
int k = low;
int start1 = low, end1 = mid;
int start2 = mid, end2 = high;
while (start1 < end1 && start2 < end2)
b[k++] = a[start1] < a[start2] ? a[start1++] : a[start2++];
while (start1 < end1)
b[k++] = a[start1++];
while (start2 < end2)
b[k++] = a[start2++];
}
int* temp = a;
a = b;
b = temp;
}
if (a != arr) {
int i;
for (i = 0; i < len; i++)
b[i] = a[i];
b = a;
}
free(b);
}
```
阅读全文