您的位置:首页 > 其它

快速排序

2017-11-26 23:57 363 查看
Code:

//空间复杂度中各种各样的数组是归并排序的一大混乱点
//#include<bits/stdc++.h>
#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
const int maxn = 1000000;
int num[maxn];
int T[maxn];
int temp[maxn];

void Merge(int s, int m, int t)
{
int i = s, j = m+1, k;
for(k = s ; i <= m && j <= t;)
{
if(temp[i] > temp[j])
T[k] = temp[j], j++, ++k;
else
T[k] = temp[i], i++, ++k;
}
while(i <= m)
T[k] = temp[i], i++, k++;
while(j <= t)
T[k] = temp[j], j++, k++;
for(int ii = s; ii <= t; ii++)
temp[ii] = T[ii];
return ;
}

void M_Sort(int s, int t)
{
if(s == t)
{
temp[s] = num[s]; //只有一个元素
T[s] = num[s];
}
else
{
int m = (s+t)/2; //确定中间元素的位置
M_Sort(s, m); //将num数组的[s, m]归并为有序的TR2
M_Sort(m+1, t); //将num数组的[m+1, t]归并为有序的TR2
Merge(s, m, t); //讲TR2中的[s, m] 和 [m+1]合并为TR1
}
}

int main()
{
int n;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &num[i]);
M_Sort(1, n);
for(int i = 1; i <= n; i++)
if(i == 1) cout << T[i];
else cout << " " << T[i];
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: