SOURCE

function swap(arr, i, j) {
    const temp = arr[i]
    arr[i] = arr[j]
    arr[j] = temp
}

function getRandomArray(size = 10) {
    return Array(size).fill(undefined).map((_) => Math.floor(Math.random() * size * 2))
}

function quickSort(arr, start = 0, end = arr.length-1) {
    if (start >= end) return

    const pivotIndex = partition(arr, start, end)
    quickSort(arr, start, pivotIndex-1)
    quickSort(arr, pivotIndex+1, end)

    return arr
}

function partition(arr, left, right) {
    let i = left
    let j = right
    const x = arr[left]

    while(i < j) {
        while(i < j && arr[j] > x) {
            j--
        }

        while(i < j && arr[i] <= x) {
            i++
        }

        if (i < j) {
            swap(arr, i, j)
        }
    }

    if (arr[left] > arr[i]) {
        swap(arr, left, i)
    }

    return i
}

const arr = getRandomArray()
console.log('original arr: ', arr)
console.log('sorted arr: ', quickSort(arr))
console 命令行工具 X clear

                    
>
console