//bubble sort
?123456789101112131415161718192021222324252627282930 | function bubbleSort(arr,comp){ for (var i = 0 ;i < arr.length; i++){ for (var j = 0 ; j < arr.length - i - 1 ; j++){ if (comp(arr[j],arr[j+ 1 ])){ exch(arr,j,j+ 1 ); } } } } function exch(a,i,j){ var tmp = a[i]; a[i] = a[j]; a[j] = tmp; } var input = new Array( 5 , 1 , 4 , 2 , 3 ); bubbleSort(input,function(a,b){ return a > b;}); console.log(input); input = new Array( 5 , 1 , 4 , 2 , 3 ); bubbleSort(input,function(a,b){ return a < b;}); console.log(input); |
//selection sort
?12345678910111213141516171819202122232425262728 | function selectionSort(arr,comp){ for (var i = 0 ;i < arr.length ; i++){ for (var j = i;j < arr.length ; j++){ if (comp(arr[i],arr[j])) { exch(arr,i,j); } } } } function exch(a,i,j){ var t = a[i]; a[i] = a[j]; a[j] = t; } var input = new Array( 5 , 1 , 4 , 2 , 3 ); selectionSort(input,function(a,b){ return a > b;}); console.log(input); input = new Array( 5 , 1 , 4 , 2 , 3 ); bubbleSort(input,function(a,b){ return a < b;}); console.log(input); |
//insert sort
?1234567891011121314151617181920212223242526272829 | function insertSort(arr,comp){ var result = new Array(); for (;arr.length > 0 ;){ var inserted = false ; for (var j = 0 ;j < result.length; j++){ if (comp(result[j],arr[ 0 ])) { insert(result,j,arr[ 0 ]); inserted = true ; break ;} } if (!inserted){insert(result,result.length,arr[ 0 ]);} arr.splice( 0 , 1 ); } return result; } function insert(arr,i,v){ arr.splice(i, 0 ,v); } var input = new Array( 5 , 1 , 4 , 2 , 3 ); var ret = insertSort(input,function(a,b){ return a > b;}); console.log(ret); var input = new Array( 5 , 1 , 4 , 2 , 3 ); ret = insertSort(input,function(a,b){ return a < b;}); console.log(ret); |
//shell sort
新闻热点
疑难解答