#include<iostream>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<ctime>
using namespace std;
typedef long long ll;
typedef double ElemType;
const int N = 1e5 + 5;
ElemType ta[N];
int n;
//归并排序,速度仅次于快排,O(nlogn),稳定性算法
void MergeSort(ElemType ta[], int len)
{
ElemType *a = ta;
ElemType *tmp = (ElemType *)malloc(len * sizeof(ElemType)); //申请临时空间用于存放合并后的序列
for (int i = 1; i < len; i += i)
{
for (int j = 0; j < len; j += i*2)
{
int low = j, mid = min(j + i, len), high = min(j + i * 2, len);
int k = low;
int s1 = low, e1 = mid; //两两相邻比较之中的左区间
int s2 = mid, e2 = high; //两两相邻比较之中的右区间
while (s1 < e1 && s2 < e2) //首先分别取两区间的首元素进行比较,小者进然后++指向下一位
tmp[k++] = (a[s1] < a[s2] ? a[s1++] : a[s2++]);
while (s1 < e1) //将剩下的所有元素复制到合并序列尾
tmp[k++] = a[s1++];
while (s2 < e2) //将剩下的所有元素复制到合并序列尾
tmp[k++] = a[s2++];
}
swap(a, tmp); //将两空间地址交换,然后重复这种归并排序过程直至最终所有元素都排好序
}
if (a != ta) //如果a不等于原数组,说明原数组的地址是tmp
{
for (int i = 0; i < len; ++i) //将合并后存在a数组的元素都移到tmp(也就是原数组)里
tmp[i] = a[i];
tmp = a; //然后再把创建的临时数组地址赋给tmp释放
}
free(tmp);
}
//输入
void init()
{
cin >> n;
for (int i = 0; i < n; ++i)
cin >> ta[i];
}
//n由自己输入,n个数由随机数输入
void rinit()
{
cin >> n;
srand((int)time(NULL));
for (int i = 0; i < n; ++i)
{
ta[i] = rand();
cout << ta[i] << " ";
}
cout << endl;
}
//输出
void print()
{
for (int i = 0; i < n; ++i)
cout << ta[i] << " ";
cout << endl;
}
signed main()
{
//init();
rinit();
MergeSort(ta, n);
print();
return 0;
}
归并排序.
最新推荐文章于 2024-10-31 16:16:13 发布