Created
November 8, 2021 08:53
-
-
Save tadeaspetak/ae4363b544d3fd2b47d6d6a93dbeb8e8 to your computer and use it in GitHub Desktop.
Iterative quick sort
This file contains 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
const swap = (arr, i, j) => { | |
const temp = arr[i] | |
arr[i] = arr[j] | |
arr[j] = temp; | |
} | |
const partition = (arr, start, end) => { | |
let pivot = arr[end]; | |
let low = start; | |
for(let j = start; j < end; j++){ | |
if(arr[j] <= pivot){ | |
swap(arr, low, j); | |
low++; | |
} | |
} | |
swap(arr, low, end); | |
return low; | |
} | |
const quickSortIterative = (arr) => { | |
let stack = []; | |
stack.push({start: 0, end: arr.length - 1}); | |
while(stack.length){ | |
const { start, end } = stack.shift(); | |
const pivotIndex = partition(arr, start, end); | |
if(pivotIndex - 1 > start){ | |
stack.push({start, end: pivotIndex - 1}); | |
} | |
if(pivotIndex + 1 < end){ | |
stack.push({start: pivotIndex + 1, end}); | |
} | |
} | |
} | |
const arr = [2,4,7,1,12,3]; | |
iterativeQuickSort(arr); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment