非原地分区
function sortArray(nums) { if (nums.length <= 1) { return nums; } var pivot = Math.floor(nums.length / 2); var left = []; var right = []; for (var i = 0; i < nums.length; i++) { if (i === pivot) { continue; } if (nums[i] < nums[pivot]) { left.push(nums[i]); } else { right.push(nums[i]); } } return sortArray(left).concat([nums[pivot]], sortArray(right));}
原地分区
function swap(nums, x, y) { var temp = nums[x]; nums[x] = nums[y]; nums[y] = temp;}function partition(nums, start, end) { var pivot = start + Math.floor(Math.random() * (end - start + 1)); swap(nums, pivot, end); for (var i = start; i < end; i++) { if (nums[i] <= nums[end]) { swap(nums, start++, i); } } swap(nums, start, end); return start;}function quickSort(nums, start, end) { if (start >= end) { return; } var pivot = partition(nums, start, end); quickSort(nums, start, pivot - 1); quickSort(nums, pivot + 1, end);}function sortArray(nums) { quickSort(nums, 0, nums.length - 1); return nums;}
总结