您的位置:首页 > 其它

归并排序

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 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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法