快速排序思想
取一个值最为基准,比它大的放右边小的放左边,对左右两边的数组递归或循环执行这步,直到所有子集只有一个元素(注意arr.length <= 1时 return)
function quickSort (arr) {if (arr.length <= 1) {return arr;}let pivotIndex = Math.floor(arr.length / 2); // 取中间的脚标let pivot = arr.splice(pivotIndex, 1)[0]; // 通过脚标取出中间值let left = [];let right = [];for (let i = 0; i < arr.length; i++) {if (arr[i] < pivot) { // 比中间值小 放左边left.push(arr[i]);} else { // 大 右边right.push(arr[i]);}}let res = this.quickSort(left).concat([pivot], this.quickSort(right)); // 递归 拼接 中间值+左右数组return res;}// 换位的快速排序function quickSortTest (arr) {function patition (arr, start, end) {const pivot = arr[end];let index = start;for (let i = start; i < end; i++) {if (arr[i] < pivot) {[arr[i], arr[index]] = [arr[index], arr[i]];index++;}}[arr[index], arr[end]] = [arr[end], arr[index]];return index;}// 使用递归function quickSortR (arr, start, end) {if (start >= end) {return;}let index = patition(arr, start, end);quickSortR(arr, start, index - 1);quickSortR(arr, index + 1, end);}// 使用循环function quickSortI (arr) {let stack = [];stack.push(0);stack.push(arr.length - 1);while (stack[stack.length - 1] >=0) {let end = stack.pop();let start = stack.pop();let index = patition (arr, start, end);if (index - 1 > start) {stack.push(start);stack.push(index - 1);}if (index + 1 < end) {stack.push(index + 1);stack.push(end);}}}// quickSortI(arr);// quickSortR(arr, 0, arr.length - 1);}
http://www.ruanyifeng.com/blog/2011/04/quicksort_in_javascript.html
