首页 > 网站 > WEB开发 > 正文

8大排序算法总结 JS 实现

2024-04-27 14:15:12
字体:
来源:转载
供稿:网友

8大排序算法总结 JS 实现

//bubble sort

?
123456789101112131415161718192021222324252627282930function 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

?
12345678910111213141516171819202122232425262728function 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

?
1234567891011121314151617181920212223242526272829function 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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表