Skip to content

Instantly share code, notes, and snippets.

@avanavana
Last active May 28, 2024 06:18
Show Gist options
  • Save avanavana/54872dc886266c352de54628fbda8806 to your computer and use it in GitHub Desktop.
Save avanavana/54872dc886266c352de54628fbda8806 to your computer and use it in GitHub Desktop.
[Algorithms] Quick Sort (Middle Pivot, Optimized) - TypeScript Implementation
/**
* @file algorithm-quickSort.ts - A TypeScript implementation of the Quick Sort algorithm using recursion, incrementing/decrementing pointers instead of array mutation for optimization of space complexity, and a pivot selected in the middle (or just to the left of the middle) of an input array
* @author Avana Vana
* @desc Algorithmic complexity:
* - Time complexity: Ω(n log(n)), Θ(n log(n)), O(n^2) (rare)
* - Space complexity: O(log(n))
*/
/**
* @function quickSort
* @desc Sorts an input array according to the Quick Sort algorithm with recursion and the pivot set to the middle (or element immediately to left of the middle in arrays of even length) element and returns the sorted array
* @template T
* @param {T[]} arr - input array of type T
* @param {number} [left=0] - minimum index of {@link arr}, zero-indexed, at which to begin sorting (used mainly for internal recursion)
* @param {number} [right={@link arr.length} - 1] - maximum index of {@link arr}, zero-indexed, at which to begin sorting (used mainly for internal recursion)
* @returns {T[]} Sorted input array
*/
function quickSort<T>(arr: T[], left: number = 0, right: number = arr.length - 1): T[] {
if (arr.length > 1) {
let i = sortPartition(arr, left, right);
if (left < i - 1) quickSort(arr, left, i - 1);
if (right > i) quickSort(arr, i, right);
}
return arr;
}
/**
* @function sortPartition
* @desc Helper function that sorts a partition of the input array by chosing a pivot in its middle
* @template T
* @param {T[]} arr - input array of type T
* @param {number} [left=0] - minimum index of {@link arr}, zero-indexed, at which to begin sorting (used mainly for internal recursion)
* @param {number} [right={@link arr}.length - 1] - maximum index of {@link arr}, zero-indexed, at which to begin sorting (used mainly for internal recursion)
* @returns {number} Minimum index for the next iteration of recursion, zero-indexed
*/
function sortPartition<T>(arr: T[], left: number, right: number): number {
let pivot = arr[Math.floor((left + right) / 2)];
while (left <= right) {
while (arr[left] < pivot) left++;
while (arr[right] > pivot) right--;
if (left <= right) [ arr[left++], arr[right--] ] = [ arr[right], arr[left] ];
}
return left;
}
quickSort([ 3, 7, 5, 2, 6, 1, 0, 4 ]);
// > [ 0, 1, 2, 3, 4, 5, 6, 7 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment