码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序

时间:2015-08-28 23:20:09      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:算法

归并排序算法很容易描述。如果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];
} 

版权声明:本文为博主原创文章,未经博主允许不得转载。

归并排序

标签:算法

原文地址:http://blog.csdn.net/hacker_no_1/article/details/48064307

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!