Skip to content

Instantly share code, notes, and snippets.

@malulleybovo
Created March 21, 2019 01:09
Show Gist options
  • Save malulleybovo/7491e5f33ca07d39d62246fa89ddace2 to your computer and use it in GitHub Desktop.
Save malulleybovo/7491e5f33ca07d39d62246fa89ddace2 to your computer and use it in GitHub Desktop.
Implementation of Randomized Quick Sort Algorithm
// Sorts array in ascending order
function quickSort(arr) {
if (arr == null
|| !Array.isArray(arr)) return;
mQuickSort(arr, 0, arr.length);
function mQuickSort(arr, startIdx, endIdx) {
if (endIdx - startIdx <= 1) return;
if (endIdx - startIdx == 2 && arr[0] > arr[1]) {
var t = arr[1];
arr[1] = arr[0];
arr[0] = t;
return;
}
var pivotIdx = Math.floor(Math.random() * (endIdx - startIdx)) + startIdx;
var pivot = arr[pivotIdx];
arr[pivotIdx] = arr[endIdx - 1];
arr[endIdx - 1] = pivot;
var i = startIdx;
for (var j = startIdx; j < endIdx - 1; j++) {
if (arr[j] <= pivot) {
var t = arr[j];
arr[j] = arr[i];
arr[i] = t;
i++;
}
}
arr[endIdx - 1] = arr[i];
arr[i] = pivot;
mQuickSort(arr, startIdx, i);
mQuickSort(arr, i + 1, endIdx);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment