归并排序(C++代码)

 1 #include<iostream>
 2 using namespace std;
 3 int pt[1000001];
 4 int pr[1000001];
 5 void mergesort(int*,int*,int,int);
 6 int main()                      //归并排序
 7 {
 8     int num,i=0,j,left,right;
 9 
10     while(cin>>num)
11     {
12         pt[i++]=num;
13         if(cin.get()=='\n')  break;
14     }
15     left=0;
16     right=i-1;
17 
18     for(i=left;i<=right;i++)
19         pr[i]=pt[i];
20 
21     mergesort(pt,pr,left,right);
22     for(j=0;j<=right;j++)
23         cout<<pt[j]<<" ";
24 
25 }
26 
27 void mergesort(int*pt,int*pr,int left,int right)
28 {
29     int mid=(left+right)/2;
30     if(left==right) return;
31     mergesort(pt,pr,left,mid);
32     mergesort(pt,pr,mid+1,right);
33 
34     int i1=left;int i2=mid+1;
35 
36     for(int curr=left;curr<=right;curr++)
37     {
38        if(i1==mid+1)
39            pt[curr]=pr[i2++];
40        else if(i2>right)
41            pt[curr]=pr[i1++];
42        else if(pr[i1]<pr[i2])
43            pt[curr]=pr[i1++];
44        else 
45            pt[curr]=pr[i2++];
46     
47     }
48 
49 
50 }

 

posted on 2012-11-30 20:42  Besion王  阅读(298)  评论(1编辑  收藏  举报

导航