首页 > 代码库 > 归并排序

归并排序

归并排序,具体如下图:

代码实现:

function merger( a, b ){    var array = [], m = a.length, n = b.length;    for(var i = 0, j = 0; i < m && j <n ){        if(a[i] > b[j]){            array.push(b[j]);            ++j;        }else{            array.push( a[i] );            ++i;        }    }    while( i < m ){        array.push( ret[i] );        ++i;    }    while( j < n ){        array.push( ret[j] );        ++j;    }    return array;}function mergerSort(arr){    if(arr.length <= 1) return arr;    var position = Math.floor(arr.length/2);    var a = arr.slice(0 , position);    var b = arr.slice (position);    return merger( mergerSort(a), mergerSort(b) );} 

 

归并排序