Quick Sort

PHOTO EMBED

Wed Oct 19 2022 13:40:46 GMT+0000 (Coordinated Universal Time)

Saved by @RedJohn

const pivot = (arr, startIndex = 0, lastIndex = arr.length + 1) => {
    const swap = (arr, i, j) => {
        let temp = arr[i]
        arr[i] = arr[j]
        arr[j] = temp
    }
    let pivotVal = arr[startIndex]
    let swapIndex = startIndex
    for(let i = startIndex + 1; i < arr.length; i++) {
        if(pivotVal > arr[i]) {
            swapIndex++;
            swap(arr, swapIndex, i)
        }
    }
    swap(arr,startIndex, swapIndex)
    return swapIndex
}

const quickSort = (arr, left = 0, right = arr.length - 1) => {
    if(left < right) {
        let pivotIndex = pivot(arr, left, right)
        quickSort(arr, left, pivotIndex - 1)
        quickSort(arr, pivotIndex + 1, right)
    }
    return arr
}

quickSort([10,3,2,9,5])
content_copyCOPY