Created
October 13, 2021 19:11
-
-
Save KEIII/43c1fe5e305b20a20087bcf051c12117 to your computer and use it in GitHub Desktop.
Quicksort
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
const swap = (items, first, second) => { | |
const tmp = items[first]; | |
items[first] = items[second]; | |
items[second] = tmp; | |
}; | |
const partition = (items, left, right) => { | |
const pivot = items[Math.trunc((right + left) / 2)]; | |
while (left <= right) { | |
while (items[left] < pivot) left++; | |
while (items[right] > pivot) right--; | |
if (left <= right) { | |
swap(items, left, right); | |
left++; | |
right--; | |
} | |
} | |
return left; | |
}; | |
export const qsort = (items) => { | |
if (items.length < 2) return; | |
const go = (items, left, right) => { | |
if (left >= right) return; | |
const mid = partition(items, left, right); | |
go(items, left, mid - 1); | |
go(items, mid, right); | |
}; | |
go(items, 0, items.length - 1); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment