归并排序

  今天写的是归并排序,废话不多说了,贴上代码。来自于Introduction to Algorithms。

void MergeSort(int * x, int n){
M_Sort(x, 0, n - 1);
}

void M_Sort(int * x, int left, int right){//the real MergeSort
int middle = 0;
if ( right - left == 1){
if ( x[left] > x[right] )
Exchange(x[left], x[right]);
}
else if ( left != right ){
middle = ( right + left ) / 2;
M_Sort(x, left, middle);
M_Sort(x, middle + 1, right);
//Merge
int * temp = new int[right - left + 1];
int i = left;
int j = middle + 1;
int k = 0;
while ( i <= middle && j <= right ){
if ( x[i] <= x[j] ){
temp[k] = x[i];
i++;
}
else{
temp[k] = x[j];
j++;
}
k++;
}
/*若左边的序列都已在正确的位置上,则右边的序列也就在正确的位置上了,不需变化
若右边的序列都已在正确的位置上,则需要把左边序列中剩余的部分移至序列的最后
*/
if ( j > right ){
for ( int t = 0; t <= middle - i; t++ ){
x[right - t] = x[middle - t];
}
}
//将temp复制回x
for ( int t = 0; t < k; t++ ){
x[left + t] = temp[t];
}
delete [] temp;
}
return;
}

void Exchange(int &a, int &b){
int temp = a;
a = b;
b = temp;
return;
}

  复杂度:归并两个长度分别为m,n的序列需O(n+m)次比较和移动,在最坏情况下,到底需要几次比较呢,怎样的两个序列是最坏情况。。。大家可以想一想,这里也就不什么都说明白了,思考有助于理解。考虑一个长度为n的序列,采用归并排序需要O(nlogn)的比较和O(nlogn)的数据移动。

  在n较大的情况下,归并排序优于插入排序,但是归并排序有两个缺点:1.不易实现2.需要额外的存储空间。

  P.S:还是希望看过的同学提提意见。。。


posted @ 2011-11-20 02:49  Fooving  阅读(1062)  评论(0编辑  收藏  举报