归并排序

归并排序的程序:

      

 void

mergeSort(int a[], int first, int last, int temp[])

{

         int mid ;

         if ( first < last)

        {

              mid  = (first + last)/2;   

              //分解

              mergeSort(a,first,mid,temp);

              mergeSort(a,mid +1,last,temp);

              //合并

             mergeArray(a,first,mid,last,temp);

        }

}

 

void

mergeArray(int a[], int first, int mid, int last, int temp[])

{

       int  i = first,j = mid+1;

       int  m = mid, n =last;

       int  k =0;

       while ( i <= m && j <=n)

      {        

                  //a[i],a[j]比较放入临时数组temp中

                  if(a[i] < a[j])

                      temp[k++] = a[i++];

                 else 

                      temp[k++] = a[j++]; 

        } 

         //将剩余的数据放入数组temp中

          while( i <= m)

                     temp[k++] = a[i++];

           while(j <= n)

                     temp[k++] = a[j++];

          for( i = 0; i< k; i++)

                      a[first + i] = temp[i];

posted @ 2012-09-07 15:52  风去无痕  阅读(87)  评论(0编辑  收藏  举报