2020-01-28 快速排序(原地排序)
2020-01-28 本文已影响0人
人拆
function swap(arr, i, j) {
const temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
function partition(arr, pIndex, left, right) {
const p = arr[pIndex]
let startIndex = left
for (let i = left; i < right; i++) {
if (arr[i] < p) {
swap(arr, i, startIndex)
startIndex++
}
}
swap(arr, startIndex, pIndex)
return startIndex
}
function quick_sort_c(arr, left, right) {
if (left < right) {
let pIndex = right
let partitionIndex = partition(arr, pIndex, left, right)
quick_sort_c(arr, left, partitionIndex - 1 < left ? left : partitionIndex - 1)
quick_sort_c(arr, partitionIndex + 1 > right ? right : partitionIndex + 1, right)
}
}
function quickSort(arr) {
const len = arr.length
if (len <= 1) return arr
return quick_sort_c(arr, 0, len - 1)
}