## 每周一算法之四——归并排序

2011-12-13 23:20  贼寇在何方  阅读(141)  评论(0编辑  收藏

// 归并排序// C++实现#include <iostream>using namespace std;template<class T>void merge(T array[], int low, int high, int middle){    int begin1 = low;    int end1 = middle;    int begin2 = middle+1;    int end2 = high;    int count = 0;    T *buffer = new T[high-low+1];        // 每次取两个序列中较小的值存放    while( begin1 <= end1 && begin2 <= end2 )    {        if(array[begin1] <= array[begin2])        {            buffer[count++] = array[begin1++];        }        else        {            buffer[count++] = array[begin2++];        }    }        // 复制序列余下的部分    if( begin1 <= end1 )    {        memcpy(buffer+count, array+begin1, (end1-begin1+1)*sizeof(T));    }    if( begin2 <= end2 )    {        memcpy(buffer+count, array+begin2, (end2-begin2+1)*sizeof(T));    }    memcpy(array+low, buffer, (high-low+1)*sizeof(T));    delete []buffer;}template<class T>void merge_sort(T array[], int low, int high){    if(low < high)    {        int middle = low/2 + high/2;        merge_sort(array, low, middle);        merge_sort(array, middle+1, high);        merge(array, low, high, middle);    }}template<class T>void merge_sort(T array[], const int size){    merge_sort(array, 0, size);}int main(void){    int array[] = {2, 5, 9, 3, 12, 1, 6, 11, 4, 7, 13, 8, 10};    merge_sort(array, sizeof(array) / sizeof(int));    for (int i = 0; i < sizeof(array) / sizeof(int); i ++)        cout<<array[i]<<endl;                return 0;}