Skip to content

Instantly share code, notes, and snippets.

@batogov
Created August 21, 2017 08:53
Show Gist options
  • Save batogov/92201755d3f1e709e1174922bb58633f to your computer and use it in GitHub Desktop.
Save batogov/92201755d3f1e709e1174922bb58633f to your computer and use it in GitHub Desktop.
QuickSort [JavaScript]
function swap(arr, firstIndex, secondIndex) {
const buf = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = buf;
}
function partition(arr, left, right) {
let pivot = arr[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (arr[i] < pivot) {
i++;
}
while (arr[j] > pivot) {
j--;
}
if (i <= j) {
swap(arr, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(arr, left = 0, right = arr.length - 1) {
let i;
if (arr.length > 1) {
i = partition(arr, left, right);
if (left < i - 1) {
quickSort(arr, left, i - 1);
}
if (i < right) {
quickSort(arr, i, right);
}
}
return arr;
}
console.log(quickSort([4, 1, 10, 0, 15]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment