To find the kth smallest element in an array, we can sort the array and then return the element at index k-1. One way to sort the array is to use the built-in sort
method.
main.rb94 chars5 lines
Another way to sort the array is to use a more efficient algorithm, such as quicksort or heapsort. One implementation of quicksort could look like this:
main.rb415 chars26 lines
Note that this implementation of quicksort picks a random pivot element to help avoid worst-case performance when the input array is already sorted or nearly sorted.
gistlibby LogSnag