归并排序
2015-08-28 22:48
239 查看
归并排序算法很容易描述。如果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是四参数递归函数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]; }
相关文章推荐
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析
- C#获取关键字附近文字算法实例