归并排序c++和javascript实现

来源:互联网 发布:日剧知乎 编辑:程序博客网 时间:2024/06/05 22:12

归并排序有递归和迭代两种方式,递归的很好理解,所以一会儿只发一下js写的,因为更精炼一点。迭代实现的理解重点:1.步长每次乘二。2.最后剩下的一部分记得加到结果数组里去

javascript:

/*归并排序--两个元素的重排列*/function merge(left,right){var result = [];while(left.length > 0 && right.length > 0){if(left[0] < right[0]){result.push(left.shift());}else{result.push(right.shift());}}return result.concat(left).concat(right);}/*归并排序--递归*/function mergeSort(items){if(items.length == 1){return items;}var middle = Math.floor(items.length /2),left = items.slice(0,middle),right = items.slice(middle);return merge(mergeSort(left),mergeSort(right));}var items = [1,2,9,8,3,4,7,6,5,6,5,4];var result = mergeSort(items);result.forEach(function(value,index,array){console.log(value);});/*归并排序--迭代*/function mergeSort2(items){if(items.length == 1){return items;}var work = [];for(var i=0,len=items.length;i<len;i++){work.push([items[i]]);}work.push([]);for(var lim=len;lim>1;lim=(lim+1)/2){for(var j=0,k=0;k<lim;j++,k+=2){work[j] = merge(work[k],work[k+1]);}work[j] = [];}return work[0];}result = mergeSort2(items);result.forEach(function(value,index,array){console.log(value);});

c++:

#include<iostream>#include<algorithm>using namespace std;template <class T>void Merge(T* initList, T* mergedList, const int l, const int m, const int n){    int i1, i2, iResult;    for(i1 = l, iResult = l, i2 = m + 1; i1 <= m && i2 <= n; iResult++)    {        if(initList[i1] <= initList[i2])        {            mergedList[iResult] = initList[i1];            i1++;        }        else        {            mergedList[iResult] = initList[i2];            i2++;        }    }    copy(initList+i1, initList+m+1, mergedList+iResult);    copy(initList+i2, initList+n+1, mergedList+iResult);}template <class T>void MergePass(T* initList, T* ResultList, const int n, const int s){    int i;    for(i = 1; i <= n-2*s+1; i += 2*s)    {        Merge(initList, ResultList, i, i+s-1, i+2*s-1);    }    if((i+s-1) < n)    {        Merge(initList, ResultList, i, i+s-1, n);    }    else    {        copy(initList+i, initList+n+1, ResultList+i);    }}template <class T>void MergeSort(T* a, const int n){    T* tempList = new T[n+1];    for(int l = 1; l < n; l *= 2)    {        MergePass(a, tempList, n, l);        l*=2;        MergePass(tempList, a, n, l);    }    delete [] tempList;}int main(void){    int arr[11] = {0, 26, 5, 77, 1, 61, 11, 59, 15, 48, 19};    MergeSort(arr,11);    for(int i = 1; i < 11; i++)    {        cout << arr[i] << " ";    }    cout << endl;    return 0;}


0 0