Skip to content

Instantly share code, notes, and snippets.

@olegon
Created January 13, 2017 19:23
Show Gist options
  • Save olegon/028574fa35a5e2b6ecb64a853ef4d672 to your computer and use it in GitHub Desktop.
Save olegon/028574fa35a5e2b6ecb64a853ef4d672 to your computer and use it in GitHub Desktop.
Quicksort Algorithm
/*
Quicksort Algorithm
*/
function quicksort(array) {
function partition(a, start, end) {
let i = start,
j = end + 1;
while (true) {
while (a[++i] < a[start]) {
if (i == end) break;
}
while (a[--j] > a[start]) {
if (j == start) break;
}
if (i >= j) break;
let c = a[i];
a[i] = a[j];
a[j] = c;
}
let c = a[start];
a[start] = a[j];
a[j] = c;
return j;
}
function sort(a, start, end) {
if (start >= end) return;
const j = partition(a, start, end);
sort(a, start + 1, j - 1);
sort(a, j + 1, end);
}
sort(array, 0, array.length - 1);
}
const array = [7, 5, 10, 3, 4];
quicksort(array);
console.log(array);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment