find the kth largest element in an array in ruby

One way to find the kth largest element in an array is to sort the array in descending order and then return the kth element. Here's how you can do it in Ruby:

main.rb
def kth_largest(arr, k)
  sorted_arr = arr.sort.reverse
  return sorted_arr[k - 1]
end
87 chars
5 lines

This method takes an array arr and an integer k as input. It first sorts the array in descending order using the sort method, and then reverses it using the reverse method. The kth largest element is then obtained by indexing into the sorted array at index k - 1. Note that the k value is assumed to be valid and less than or equal to the length of the array.

Here's an example usage of this method:

main.rb
my_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
puts kth_largest(my_array, 3)  # prints 5
87 chars
3 lines

In this example, the third largest element in the array [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5] is 5. The kth_largest method returns this value.

gistlibby LogSnag