#include<iostream>
using namespace std;
//将有序表 a[low.. mid]和a[mid+1. .high]归并为有序表 b[low.. high]
void merge(int a[], int low, int mid, int high) {
//b数组暂存合并的有序序列
int *b = new int[high - low + 1];
int i = low, j = mid + 1, k = 0;
//将a中记录较小值复制到b中
while (i <= mid && j <= high) {
//两个元素相等时,优先使⽤靠前的那个(稳定性)
if (a[i] <= a[j]) {
b[k++] = a[i++];
} else {
b[k++] = a[j++];
}
}
//没有归并完的部分复制到尾部
while (i <= mid) {
b[k++] = a[i++];
}
while (j <= high) {
b[k++] = a[j++];
}
//将排好序的存回a中low到high这区间
for (i = low, k = 0; i <= high; i++, k++) {
a[i] = b[k];
}
delete []b;//释放内存,由于指向的是数组,必须用delete []
}
//归并排序
void mergeSort(int a[], int low, int high) {
if (low < high) {
int mid = (low + high) / 2;//从中间划分
mergeSort(a, low, mid); //对左半部分归并排序
mergeSort(a, mid + 1, high); //对右半部分归并排序
merge(a, low, mid, high); //归并
}
}
void printArr(int a[], int len) {
for (int i = 0; i < len; i++) {
printf("%d ", a[i]);
}
printf("\n");
}
int main() {
int arr[7] = {23, 54, 12, 4, 5, 6, 32};
int len = sizeof(arr) / sizeof(int);
printArr(arr, len);
mergeSort(arr, 0, len - 1);
printArr(arr, len);
}
C++归并排序
最新推荐文章于 2024-06-01 20:09:00 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)