Skip to content

Instantly share code, notes, and snippets.

@alexeykomov
Created August 27, 2016 11:53
Show Gist options
  • Save alexeykomov/456e92569f1fb9a42eab418042bcb3d0 to your computer and use it in GitHub Desktop.
Save alexeykomov/456e92569f1fb9a42eab418042bcb3d0 to your computer and use it in GitHub Desktop.
function quickSort(aInput, aLeftIndex, aRightIndex) {
if (aInput.length > 1) {
const delimeter = partition(aInput, aLeftIndex, aRightIndex);
if (aLeftIndex < delimeter - 1) {
quickSort(aInput, aLeftIndex, delimeter - 1);
}
if (delimeter < aRightIndex) {
quickSort(aInput, delimeter, aRightIndex);
}
}
}
function partition(aArray, aLeftIndex, aRightIndex) {
let counterFromLeft = aLeftIndex;
let counterFromRight = aRightIndex;
let pivot = aArray[aLeftIndex + Math.floor((aRightIndex - aLeftIndex) / 2)];
while (counterFromLeft <= counterFromRight) {
while (aArray[counterFromLeft] < pivot) {
counterFromLeft++;
}
while (aArray[counterFromRight] > pivot) {
counterFromRight--;
}
if (counterFromLeft <= counterFromRight) {
swap(aArray, counterFromLeft, counterFromRight);
counterFromLeft++;
counterFromRight--;
}
}
return counterFromLeft;
}
function swap(aArray, aLeftIndex, aRightIndex) {
const temp = aArray[aLeftIndex];
aArray[aLeftIndex] = aArray[aRightIndex];
aArray[aRightIndex] = temp;
}
const array = [10, 2, 12, 2, 32, 2, 12, 3, 2];
quickSort(array, 0, array.length - 1);
console.log(array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment