下面我们用两种方法实现冒泡排序:
var afterDelete = [11, 2, 6, 31, 5]
方法一:
function range(arr) { for(var i=0;i<arr.length-1;i++){ //索引值是i的数字和排在它后面的所有数字依次比较一次 for (var j = i + 1;j < arr.length;j++){ if (arr[i] > arr[j]) { var temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } return arr } var rangeResult = range(afterDelete) console.log(rangeResult) // [2, 5, 6, 11, 31]
方法二:
function quickSort(elements){ if(elements.length<=1){ return elements; } var index = Math.floor(elements.length/2); //console.log(index);//5->5->4->3->2->2->1 var pivot = elements.splice(index,1)[0];//获取删除的数字 //console.log("pivot="+pivot);//1-8-7-3-6-4.4-5.5 var arrLeft = []; var arrRight = []; for(var i = 0;i<elements.length;i++){ if(elements[i] < pivot){ arrLeft.push(elements[i]); // console.log("arrLeft="+arrLeft); }else{ arrRight.push(elements[i]); // console.log("arrright="+arrRight) } } return quickSort(arrLeft).concat([pivot],quickSort(arrRight)); } console.log(quickSort(afterDelete)); // [2, 5, 6, 11, 31]