首页 > 技术文章 > 归并排序

ZRBYYXDM 2016-02-15 19:54 原文

在一些语言(例如Java)中,当排序一般的对象时,元素的比较耗时很多,但是移动元素就快得多。在所有流行的排序算法中,归并排序使用最少次数的比较。因此,在Java中,归并排序是一般目的排序的最佳选择。

 

编码实现如下:

#include <iostream>
#include <vector>

using namespace std;

template <typename Comparable>
void mergeSort( vector<Comparable> &a,
                vector<Comparable> &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 );                  //最后合并两个有序表
    }
}

template <typename Comparable>
void mergeSort( vector<Comparable> &a )                             //驱动函数
{
    vector<Comparable> tmpArray( a.size() );

    mergeSort( a,tmpArray,0,a.size() - 1 );
}

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 numElement = rightEnd - leftPos + 1;

    while( leftPos <= leftEnd && rightPos <= rightEnd )             //主循环将两部分循环复制进临时数组
        if ( a[leftPos] <= a[rightPos] )
            tmpArray[tmpPos++] = a[leftPos++];
        else
            tmpArray[tmpPos++] = a[rightPos++];

    while ( leftPos <= leftEnd )                                    //将剩余的部分拷贝
        tmpArray[tmpPos++] = a[leftPos++];

    while ( rightPos <= rightEnd )
        tmpArray[tmpPos++] = a[rightPos++];

    for ( int i = 0 ; i < numElement ; i++,rightEnd-- )
        a[rightEnd] = tmpArray[rightEnd];
}

int main()
{
    cout << "请输入一些数据:" << endl;

    vector<int> vec;
    int temp;

    while ( cin >> temp )
        vec.push_back( temp );

    mergeSort( vec );

    cout << "按升序排列过的数据如下:" << endl;

    vector<int>::iterator iter = vec.begin();
    while( iter != vec.end() )
        cout << *iter++ << endl;

    return 0;
}

 

推荐阅读