Here is a TypeScript function to find the kth smallest element in an array, using the QuickSelect algorithm:
index.ts553 chars24 linesThe arr parameter is the array to search, and the k parameter is the index of the element to find (starting at 1 for the first smallest).
The function randomly selects a pivot element from the array and partitions the remaining elements into two subarrays: one with elements smaller than the pivot, and one with elements larger than the pivot. It then recursively calls itself on the appropriate subarray until the kth element is found. The partitioning is done in linear time (O(n)), so the overall time complexity of the algorithm is O(n) on average.
To use the function, simply call it with an array and the index of the element you want to find:
index.ts164 chars5 linesThis will output:
index.ts31 chars2 lines
gistlibby LogSnag