常规方法
function sort_bubble(arr) { var temp; for(var i = 0; i < arr.length;i ++) { for(var j = i + 1;j < arr.length;j++) { if (arr[i] > arr[j]) { temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } return arr; } var result = sort_bubble([1,3,5,2,64,4]); console.log(result);
es6 对象解构赋值实现
function sort_bubble(arr) { for(let x = 0; x < arr.length; x ++) { for (let y = x + 1; y < arr.length; y ++) { [arr[x],arr[y]] = arr[x] > arr[y]?[arr[y],arr[x]]:[arr[x],arr[y]]; } } return arr; } let result = sort_bubble([1,3,2,5,4,7]); console.log(result);
传入两个参(arr,fn),控制升序,降序
function sort_bubble(arr,fn) { let length = arr.length; for(let x = 0; x < length; x ++) { for (let y = x + 1; y < length; y ++) { [arr[x],arr[y]] = fn(arr[x],arr[y])?[arr[y],arr[x]]:[arr[x],arr[y]]; } } return arr; } function ascending(x,y) { return x > y; } function desending(x,y) { return x < y; } let result1 = sort_bubble([1,3,2,5,2,1,1,2,5,4,7],ascending); let result2 = sort_bubble([1,3,2,5,2,1,1,2,5,4,7],desending); console.log(result1); console.log(result2);
JavaScript 冒泡排序
猜你喜欢
转载自www.cnblogs.com/rosendolu/p/10592914.html
今日推荐
周排行