Node.js examples for Algorithm:Sort
Array merge sort
function mergesortSingle( array ) { var mid = Math.floor( array.length / 2 ); var left = array.slice(0, mid); var right = array.slice(mid); if( left.length > 1 ) left = mergesort( left ); if( right.length > 1 ) right = mergesort( right ); result = [];//from w w w . j a v a 2s . c om while( left.length && right.length ) { if( left[left.length - 1 ] > right[ right.length - 1 ] ) { result.push( left.pop() ) } else { result.push( right.pop() ); } } result.reverse(); if( left.length ) return left.concat( result ); else return right.concat(result); } var unsortedA = []; var unsortedB = []; for(var i = 0; i < 2000000; ++i) { unsortedA.push( Math.round( Math.random() * 2000 ) ); // unsortedB.push( Math.round( Math.random() * 2000 ) ); } unsortedB = unsortedA.concat(); var start = Date.now(); unsortedB.sort(); var end = Date.now(); console.log("RegSort = " , end-start ); var start = Date.now(); // unsortedA.mergesort() unsortedA = mergesort( unsortedA ); var end = Date.now(); console.log("MergeSort = " , end-start);