C语言-排序-归并排序

思想:运用分治法思想解决排序问题。

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
void Merge(int A[],int low,int mid,int high)     
 {     
     int i,j,k;   
     int *P = new int[mid-low+1],*Q = new int[high-mid];     
      
     for (i =0;i  < mid - low +1;++i)   P[i] = A[i+low];
           
     for (i = 0; i  < high - mid;++i)   Q[i] = A[mid+1+i];     
       
     i = j = 0,k = low;     
     while ((i  <= mid-low) && (j  <= high-mid-1))     
     {     
       
         if (P[i]  <= Q[j])   A[k++] = P[i++];     
         else  A[k++]= Q[j++];     
     }     
       
     if (i > mid - low)   { for (;j  <= high-mid-1;++j)   A[k++] = Q[j]; }     
     else    
     {   for (; i <= mid - low;++i)   A[k++] = P[i];  }     
       
     delete [] P;     
     delete [] Q;     
 }     
       
 void mergeSort(int A[],int left,int right)     
 {     
     if (left  < right)     
     {     
         int i = (left + right) / 2;     
         MergeSort(A,left,i);     
         MergeSort(A,i+1,right);     
         Merge(A,left,i,right);     
     }     
 }     

  

posted @   AbbySec  阅读(219)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示