From 016f31d703c169a6a155fa87e6d4f73d6ff91331 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:53:16 +1000 Subject: [PATCH] Algorithms: Implement Quick Sort --- Algorithms/quicksort.js | 65 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 Algorithms/quicksort.js diff --git a/Algorithms/quicksort.js b/Algorithms/quicksort.js new file mode 100644 index 0000000..8dd745b --- /dev/null +++ b/Algorithms/quicksort.js @@ -0,0 +1,65 @@ +// 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]));