手写归并排序(MergeSort)

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<algorithm>
 4 
 5 #define N 10000
 6 using namespace std;
 7 
 8 void Merge(int *b,int *a,int i,int m,int n)
 9 {
10     int s = i;
11     int j,k;
12     //归并
13     for(j=m+1,k=i;i<=m&&j<=n;k++)
14     {
15         if(b[i]<b[j])    a[k]=b[i++];
16         else a[k]=b[j++];
17     }
18     while(i<=m)  
19         a[k++]=b[i++];
20     while(j<=n)
21         a[k++]=b[j++];
22     
23     for(j=s;j<=n;j++)  //将归并结果再次存入b数组
24         b[j]=a[j];
25 }
26 
27 void MergeSort(int * b,int *a,int s,int t)
28 {
29     if(s==t)    b[s]=a[s];  //初始化b数组
30     else
31     {
32         int mid = (s+t)>>1;
33         MergeSort(b,a,s,mid);  
34         MergeSort(b,a,mid+1,t);
35         Merge(b,a,s,mid,t);  //将b数组[s,mid]与[mid+1,t]归并到a中的[s,t]中
36     }
37 }
38 
39 int a[N],b[N];
40 
41 int main()
42 {
43     int n,i;
44     scanf("%d",&n);
45     for(i=1;i<=n;i++)
46     {
47         scanf("%d",a+i);
48     }
49     MergeSort(b,a,1,n);
50     for(i=1;i<=n;i++)
51     {
52         printf("%d ",a[i]);
53     }
54     putchar(10);
55     return 0;
56 }

 

posted @ 2013-08-06 22:33  crazy_apple  阅读(485)  评论(0编辑  收藏  举报