首页 > 代码库 > 二路归并排序

二路归并排序

#include <iostream>using namespace std;void merge(int* ptr,int first, int mid, int last){        int len = last - first + 1;    int *temp = new int[len];            int i = first, j = mid + 1, k = 0;    while(i <= mid && j <= last)    {        if(ptr[i] <= ptr[j])        {            temp[k++] = ptr[i++];        }        else        {            temp[k++] = ptr[j++];        }    }    while(i<=mid)    {        temp[k++] = ptr[i++];    }    while(j<=last)    {        temp[k++] = ptr[j++];    }    for( k =0;k < len; ++k)    {        ptr[first++] = temp[k];    }    delete [] temp;}void mergeSort(int *ptr,int first,int last){    if (first < last)    {        int mid = (first + last)/2;        mergeSort(ptr,first,mid);        mergeSort(ptr,mid+1,last);        merge(ptr,first,mid,last);    }}int main(){    int a[] = {2,23,45,1,8,2,0};     for(int i =0; i <= 6; ++i)    {        std::cout << a[i] << " ";    }    cout << endl;    mergeSort(a,0,6);    for(int i =0; i <= 6; ++i)    {        std::cout << a[i] << " ";    }    std::cout << std::endl;    return 0;}

 

二路归并排序