Last active
April 7, 2024 15:08
-
-
Save avanavana/c75e3ce24fc74d1fb35cb6d9844d0dba to your computer and use it in GitHub Desktop.
[Algorithms] Quick Sort (Initial Pivot) - TypeScript Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file algorithm-quickSortInitialPivot.ts - A TypeScript implementation of the Quick Sort algorithm using recursion and the first element of the input array as a pivot | |
* @author Avana Vana | |
* @desc Algorithmic complexity: | |
* - Time complexity: Ω(n log(n)), Θ(n log(n)), O(n^2) | |
* - Space complexity: O(n) | |
*/ | |
/** | |
* @function quickSort | |
* @desc Sorts an input array according to the Quick Sort algorithm with recursion and the pivot set to the initial element and returns the sorted array | |
* @template T | |
* @param {T[]} arr - input array of type T | |
* @returns {T[]} Sorted input array | |
*/ | |
function quickSort<T>(arr: T[]): T[] { | |
if (arr.length <= 1) return arr; | |
let pivot = arr[0], left: T[] = [], right: T[] = []; | |
for (let i = 1; i < arr.length; i++) { | |
if (arr[i] < pivot) left.push(arr[i]); | |
else right.push(arr[i]); | |
} | |
return [ ...quickSort(left), pivot, quickSort(right) ]; | |
} | |
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