算法:归并排序
原创
©著作权归作者所有:来自51CTO博客作者顾道长生的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 图示过程
(1) 归并排序的流程 - (2) 合并两个有序数组的流程
- C++代码实现:
#include <bits/stdc++.h>
using namespace std;
void merge(int *a, int left, int mid, int right, int *temp)
{
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right)
{
if (a[i] <= a[j])
temp[t++] = a[i++];
else
temp[t++] = a[j++];
}
while (i <= mid)
temp[t++] = a[i++];
while (j <= right)
temp[t++] = a[j++];
t = 0;
while (left <= right)
a[left++] = temp[t++];
}
void mergesort(int *a, int left, int right, int *temp)
{
if (left < right)
{
int mid = left + (right - left) / 2;
mergesort(a, left, mid, temp);
mergesort(a, mid + 1, right, temp);
merge(a, left, mid, right, temp);
}
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++)
cin>>a[i];
int len = sizeof(a) / sizeof(int);
int *temp = (int *)malloc(sizeof(int)*len);
mergesort(a, 0, len - 1, temp);
for (int i = 0; i < len; i++)
cout << a[i] << '\t' << endl;
return 0;
}
运行效果: