快速排序
2017-11-26 23:57
281 查看
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;
}
//空间复杂度中各种各样的数组是归并排序的一大混乱点
//#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;
}
相关文章推荐
- 分治法--快速排序
- 常用排序算法C++实现(堆排序,快速排序,归并排序,基数排序)
- 快速排序【记录一下代码】
- 二进制快速排序
- 递归算法经典之快速排序
- 由快速排序到分治思想
- 面试珠玑 快速排序、希尔排序、插入排序、选择排序、归并排序、堆排序总结
- 数据结构快速排序演示
- 排序之选择排序、堆排序、归并排序、快速排序
- 算法 -- 快速排序
- 学习笔记----快速排序的java实现及其改良
- 《数据结构和Java集合框架第三版》读书笔记(十二)快速排序
- 划分--快速排序
- JavaScript 、Python Java、Go算法系列之【快速排序】篇
- (四)快速排序
- 快速排序的递归与非递归实现
- 交换排序——冒泡排序和快速排序,C++代码实现
- 快速排序
- 快速排序一轮的代码实现
- 快速排序-合并排序(分治法运用)