归并排序

归并排序算法很容易描述。如果N=1,那么只有一个元素需要排序,答案是显而易见的。否则,递归地将前半部分数据和后半部分数据各自归并排序,得到排序后的两部分数据,然后使用合并算法将这两部分合并到一起。例如,欲将8元素数组24,13,26,1,2,27,38,15排序,我们地柜地将前4个数据和后4个数据分别排序,得到1,13,24,2,15,27,38。然后,将这两部分合并,得到最后的表1,2,13,15,24,26,27,38。 该算法是经典的分治策略(divide-and-conquer),他将问题分(divide)成一些小的问题然后递归求解,而治(conquering)的阶段则是将分的阶段解得的各答案修补在一起。分治是递归非常有力的用法。
归并排序的一种实现如下所示,单参数mergeSort是四参数递归函数mergeSort的一个驱动程序。

/**
* Mergesort algorithm(driver).
* /
template   <typename Comparable>
void mergeSort(vector<Comparable> & a)
{
   vector<Comparable> tmpArray(a.size() );
   mergeSort(a,tmpArray,0,a.size()-1);
}

/**
* Internal method that make recursive calls.
* a is an array of Comparable items.
* tmpArray is an array to place the merged result.
* left is the left-most index of the subarray.
* right is the right-most index of the subarray.
* /
template <typename Comparable>
void mergeSort(vector<Comprable> & a, vector<Comprable> & tmpArray, int left,int right)
{
    if(left < right)
    {
        int center=(left+right)/2;
        mergeSort(a,tmpArray,left,center);
        mergeSort(a,tmpArray,center+1,right);
        merge(a,tmpArray,left,center+1,right);
    }
}  


/**
* Internal method that merges two sorted halves of a subarray.
* a is an array of Comparable items.
* tmpArray is an array to place the merged result.
* leftPos is the left-most index of tje subarray.
* rightPos is the index of the start of the second half.
* rightEnd is the right-most index of the subarray.
* /

template <typename Comparable>
void merge(vector<Comparable> & a,vector<Comparable>& tmpArray, int leftPos,int rightPos,int rightEnd)
{
       int leftEnd=rightPos-1;
       int tmpPos=leftPos;
       int numElements=rightEnd - leftPos + 1;
       //Main loop
       while(leftPos <=leftEnd && rightPos <= rightEnd)
          if( a[leftPos] <=a[rightPos] )
                tmpArray[ tmpPos++ ]=a[leftPos++];
          else
                tmpArray[tmpPos++]=a[rightPos++];
      while(leftPis <= leftEnd ) //Copy rest of first half
           tmpArray[tmpPos++] = a[leftPos++];
      while( rightPos <= rightEnd ) // Copy rest of right half
           tmpArray[ tmpPos++] = a[rightPos++];
     for(int i=0;i<numElements;i++,rightEnd--)
         a[rightEnd]=tmpArray[rightEnd];
} 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值