分治排序mergsort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include<iostream>
using std::cout;
using std::cin;
using std::endl;
void merge(int a[],int b[],int left,int right){
int mid=(left+right)/2;
int bc=left;
int l=left;
int r=mid+1;
while(l<=mid && r<=right){
if(a[l]<=a[r])
b[bc++]=a[l++];
else
b[bc++]=a[r++];
}
while(l<=mid && r>right){
b[bc++]=a[l++];
}
while(r<=right && l>mid){
b[bc++]=a[r++];
}
}
void copy(int a[],int b[],int left,int right){
for(int i=left;i<=right;i++){
b[i]=a[i];
}
}
void mergesort(int a[],int b[],int left,int right){
if(left<right){
int mid=(left+right)/2;
mergesort(a,b,left,mid);
mergesort(a,b,mid+1,right);
merge(a,b,left,right);
copy(b,a,left,right);
}
}
void print(int b[],int size){
for(int i=0;i<size;i++)
cout<<b[i]<<" ";
cout<<endl;
}
int main(){
cout<<"请输入需要排序的序列的大小"<<endl;
int count=0;
cin>>count;
cout<<"请输入需要排序的序列"<<endl;
int *a=new int[count];
int *b=new int[count];
for(int i=0;i<count;i++)
cin>>a[i];
mergesort(a,b,0,count-1);
print(b,count);
}