"快速排序"的思想很簡單,整個排序過程只須要三步:javascript
(1)在數據集之中,找一個基準點java
(2)創建兩個數組,分別存儲左邊和右邊的數組數組
(3)利用遞歸進行下次比較ui
var needSortArr = [12, 23, 45, 11, 2, 55, 12, 1]; function quickSort (arr) { if (arr.length <= 1) { return arr; //若是數組只有一個數,就直接返回; } var num = Math.floor(arr.length / 2), //找到中間數的索引值,若是是浮點數,則向下取整 numberOfCenter = arr.splice(num, 1), //找到中間數的值 left = [], right = []; for(var i = 0; i < arr.length; i++) { if (arr[i] < numberOfCenter) { left.push(arr[i]); } else { right.push(arr[i]); } } return quickSort(left).concat([numberOfCenter], quickSort(right)); } alert(quickSort(needSortArr));