Octave Quickselect for Kth Smallest Element
function kthElement = findKthSmallest(arr, k) % Finds the k-th smallest element in an unsorted array using the Quickselect algorithm. % Quickselect is related to Quicksort but only recurses on one side of the partition. % This makes its average time complexity O(n), but worst-cas...
This Octave code implements the Quickselect algorithm to efficiently find the k-th smallest element in an unsorted array. It's a selection algorithm that, like Quicksort, uses a partitioning strategy but only recurses on...
The `findKthSmallest` function uses the Quickselect algorithm to find the k-th smallest element in an array. It first performs input validation to ensure `k` is within valid bounds and the array is not empty. The core logic resides in the `quickselectHelper` function, which recursively partitions the array. A `partition` helper function rearranges the sub-array such that elements smaller than a chosen pivot are to its left, and larger elements are to its right. The `quickselectHelper` then determines if the pivot is the k-th element, or if the search should continue in the left or right partition. The average time complexity is O(n), as on average, one partition is discarded in each recursive step. The worst-case time complexity is O(n^2), occurring when the pivot selection consistently leads to highly unbalanced partitions (e.g., always picking the smallest or largest element). The space complexity is O(log n) on average due to recursion depth, and O(n) in the worst case. An invariant is that after `partition` completes, `arr(pivotFinalIndex)` is in its correct sorted position, and all elements before it are smaller, and all elements after it are larger.
function findKthSmallest(arr, k): n = length(arr) if n == 0: error 'empty array' if k < 1 or k > n: error 'invalid k' arrCopy = copy of arr return quickselectHelper(arrCopy, 1, n, k) function quickselectHelper(arr, low,...