algorithmpool
Version:
A pool of algorithms and data-structures for geeks
60 lines (55 loc) • 1.73 kB
JavaScript
/**
* QuickSort is an efficient sorting algorithm that utilizes the divide-and-conquer paradigm
*
* Notes:
* - Algorithm derived via Introduction to Algorithm (Cormen et al)
* - Has an optimal best and average case (O(nlgn)) but unlikely poor worst case (O(n^2))
* - Worst occurs when QuickSort produces a maximally unbalanced subproblem with n-1 elements
* and one with 0 elements, and happens through every iteration of QuickSort
* - Not stable (Other implementations of QuickSort are)
* - In-place (Other implementations of QuickSort aren't)
* - This implementation uses randomly selected pivots for better performance
*
* @complexity: O(nlgn)
*/
import {
Compare,
defaultCompare,
swap
} from '../../utils/util';
const partition = (array, left, right, compareFn) => {
const pivot = array[Math.floor((right + left) / 2)];
let i = left;
let j = right;
while (i <= j) {
while (compareFn(array[i], pivot) === Compare.LESS_THAN) {
i++;
}
while (compareFn(array[j], pivot) === Compare.BIGGER_THAN) {
j--;
}
if (i <= j) {
swap(array, i, j);
i++;
j--;
}
}
return i;
}
const quick = (array, left, right, compareFn) => {
let index;
if (array.length > 1) {
index = partition(array, left, right, compareFn);
if (left < index - 1) {
quick(array, left, index - 1, compareFn);
}
if (index < right) {
quick(array, index, right, compareFn);
}
}
return array;
}
export const quickSort = (array, compareFn = defaultCompare) => {
return quick(array, 0, array.length - 1, compareFn);
}