freeCodeCamp/Algorithms/quicksort.js

66 lines
2.0 KiB
JavaScript

// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-quick-sort
function quickSort(array) {
// Only change code below this line
const swap = (array, indexA, indexB) => {
const temp = array[indexA];
array[indexA] = array[indexB];
array[indexB] = temp;
};
const medianIndex = (array, indexA, indexB, indexC) => {
const lowerIndex = array[indexA] < array[indexB] ? indexA : indexB;
const higherIndex = array[lowerIndex] > array[indexC] ? lowerIndex : indexC;
const pivotIndex =
array[indexA] < array[higherIndex] ? indexA : higherIndex;
return pivotIndex;
};
const partition = (array, startIndex, endIndex) => {
const midIndex = Math.floor(startIndex + (endIndex - startIndex) / 2);
const pivotIndex = medianIndex(array, startIndex, midIndex, endIndex);
const pivot = array[pivotIndex];
swap(array, pivotIndex, endIndex);
let lowIndex = startIndex;
let highIndex = endIndex - 1;
while (lowIndex < highIndex) {
for (; lowIndex < highIndex; lowIndex++) {
if (array[lowIndex] > pivot) break;
}
for (; highIndex >= lowIndex; highIndex--) {
if (array[highIndex] < pivot) break;
}
if (lowIndex < highIndex) swap(array, lowIndex, highIndex);
}
if (array[lowIndex] > array[endIndex]) {
swap(array, lowIndex, endIndex);
return lowIndex;
}
return endIndex;
};
// To-do: make it non-recursive
const quicksort_ = (array, startIndex, endIndex) => {
if (startIndex < endIndex) {
const pivotIndex = partition(array, startIndex, endIndex);
if (pivotIndex - 1 > startIndex)
quicksort_(array, startIndex, pivotIndex - 1);
if (pivotIndex + 1 < endIndex)
quicksort_(array, pivotIndex + 1, endIndex);
}
};
quicksort_(array, 0, array.length - 1);
return array;
// Only change code above this line
}
console.log(
quickSort([
1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92,
])
);
console.log(quickSort([2, 6, 5, 3, 8, 7, 1, 0]));