C语言-排序-归并排序

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

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 @ 2015-09-14 03:47  AbbySec  阅读(219)  评论(0编辑  收藏  举报