算法导论----<归并排序>及实例
2016-04-05 13:15
363 查看
/*
MERGE(A,p,q,r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2+1] be new arrays
for i = 1 to n1
L[i] = A[p + i - 1]
for j = 1 to n2
R[j] = A[q+j]
L[n1 + 1] = S
R[n2 + 1] = S
i = 1
j = 1
for k = p to r
if L[i] <= R[j]
A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1
*/
#include <iostream>
#include <string.h>
using namespace std;
int i,j,k;
int A[10];
void merge(int *A,int p,int q,int r)
{
int n1 = q - p +1;
int n2 = r - q;
int *L = new int[n1+1];
int *R = new int[n2+1];
for(i = 0;i<n1;i++){
*(L+i) = *(A+p+i);
}
//哨兵元素
*(L+n1) = 1000000;
for(i = 0;i<n2;i++){
*(R+i) = *(A+q+i+1);
}
*(R+n2) = 1000000;
i = 0;
j = 0;
for(k = p;k<=r;k++)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
}
delete []L;
delete []R;
}
void mergesort(int *A,int p,int r)
{
int q;
if(p < r)
{
q = (p+r) / 2;
mergesort(A,p,q);
mergesort(A,q+1,r);
merge(A,p,q,r);
}
}
int main(){
for(i = 0;i<sizeof(A)/sizeof(A[0]);i++){
cin>>A[i];
}
mergesort(A,0,9);
for(i = 0;i<sizeof(A)/sizeof(A[0]);i++){
cout<<A[i]<<" ";
}
}
时间复杂度都是O(nlogn),空间复杂度是O(n)
MERGE(A,p,q,r)
n1 = q - p + 1
n2 = r - q
let L[1..n1 + 1] and R[1..n2+1] be new arrays
for i = 1 to n1
L[i] = A[p + i - 1]
for j = 1 to n2
R[j] = A[q+j]
L[n1 + 1] = S
R[n2 + 1] = S
i = 1
j = 1
for k = p to r
if L[i] <= R[j]
A[k] = L[i]
i = i + 1
else A[k] = R[j]
j = j + 1
*/
#include <iostream>
#include <string.h>
using namespace std;
int i,j,k;
int A[10];
void merge(int *A,int p,int q,int r)
{
int n1 = q - p +1;
int n2 = r - q;
int *L = new int[n1+1];
int *R = new int[n2+1];
for(i = 0;i<n1;i++){
*(L+i) = *(A+p+i);
}
//哨兵元素
*(L+n1) = 1000000;
for(i = 0;i<n2;i++){
*(R+i) = *(A+q+i+1);
}
*(R+n2) = 1000000;
i = 0;
j = 0;
for(k = p;k<=r;k++)
{
if(L[i] <= R[j])
{
A[k] = L[i];
i++;
}
else
{
A[k] = R[j];
j++;
}
}
delete []L;
delete []R;
}
void mergesort(int *A,int p,int r)
{
int q;
if(p < r)
{
q = (p+r) / 2;
mergesort(A,p,q);
mergesort(A,q+1,r);
merge(A,p,q,r);
}
}
int main(){
for(i = 0;i<sizeof(A)/sizeof(A[0]);i++){
cin>>A[i];
}
mergesort(A,0,9);
for(i = 0;i<sizeof(A)/sizeof(A[0]);i++){
cout<<A[i]<<" ";
}
}
时间复杂度都是O(nlogn),空间复杂度是O(n)
相关文章推荐
- linux显示-bash-4.2# 问题
- JAVA基础--容器 Set, List, Map
- MAC JDK版本切换
- 一个女孩为什么要努力
- uestc599最小花费【单调队列优化dp】
- 同步,异步,阻塞,非阻塞的Java例子
- webdriver 启动各种浏览器
- linux shell编程实例总结
- WCF遇到Oracle问题
- 搜狗2016校园招聘之算法编程解析
- Unity轻量数据保存
- 在Windows上安装FFmpeg程序
- 文本框中的fieldLabel的隐藏
- 字符编码笔记:ASCII,Unicode和UTF-8
- rem在响应式布局中的应用
- 自定义滑杆遇到的两侧圆角的问题
- 如何使用 Google Web Fonts?
- HttpWebRequest和HttpWebResponse用法小结
- 关于input标签的一些常识
- 移动前端开发之viewport的深入理解