find the kth smallest number in a list in ruby

One way to find the kth smallest number in an array is by first sorting the array in ascending order, then selecting the kth element:

main.rb
def kth_smallest(arr, k)
  arr.sort[k-1]
end
45 chars
4 lines

Here, arr.sort will sort the array in ascending order, and [k-1] will select the kth smallest element (since arrays are 0-indexed in Ruby).

An alternative approach to finding the kth smallest element in an unsorted array is to use a selection algorithm such as Quickselect or Heapselect, which have an average time complexity of O(n) and a worst-case time complexity of O(n^2), but may be faster than sorting for very large arrays or in scenarios where only a subset of the array needs to be sorted.

gistlibby LogSnag