Created
August 18, 2020 12:28
-
-
Save jasterix/b999dc18b9ce60da11e597cb13efb194 to your computer and use it in GitHub Desktop.
Quick Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function pivot(arr, start = 0, end = arr.length - 1) { | |
const swap = (arr, idx1, idx2) => { | |
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx1]]; | |
}; | |
// We are assuming the pivot is always the first element | |
let pivot = arr[start]; | |
let swapIdx = start; | |
for (let i = start + 1; i <= end; i++) { | |
if (pivot > arr[i]) { | |
swapIdx++; | |
swap(arr, swapIdx, i); | |
} | |
} | |
// Swap the pivot from the start the swapPoint | |
swap(arr, start, swapIdx); | |
return swapIdx; | |
} | |
function quickSort(arr, left = 0, right = arr.length -1){ | |
if(left < right){ | |
let pivotIndex = pivot(arr, left, right) //3 | |
quickSort(arr,left,pivotIndex-1); | |
quickSort(arr,pivotIndex+1,right); | |
} | |
return arr; | |
} | |
quickSort([100,-3,2,4,6,9,1,2,5,3,23]) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment