算法
随机选择则一个数作为基准值,将其余数按照大小分列两边
之后对两边重复以上算法
时间复杂度
注意:如果选取的基准值始终是未排序数组中的最小值,时间复杂度会变成最大 这时候可以在每一轮取基准值的时候取一个随机index的值,而不是固定index,这样就能打破之前的排序,实现左右两边未排序部分的尽量均衡
js
const input = [4,2,15,2,5,6,21,67,2,3]
const sort = (arr = []) => {
if (arr.length <= 1) return arr
const middle = Math.floor(arr.length / 2)
const base = arr[middle];
const left = [];
const right = [];
for (let i = 1; i <= middle; i++) {
const leftIndex = middle - i;
if (leftIndex >= 0) {
const val = arr[leftIndex];
if (val > base) {
right.push(val)
} else {
left.push(val)
}
}
const rightIndex = middle + i;
if (rightIndex < arr.length) {
const val = arr[rightIndex];
if (val > base) {
right.push(val)
} else {
left.push(val)
}
}
}
return sort(left).concat([base]).concat(sort(right))
}
console.log(sort(input))