find the kth largest element in an array in python

To find the kth largest element in an array, one approach is to sort the array in descending order and return the element at index k-1.

Here's the python code to do this:

main.py
def kth_largest_element(arr, k):
    sorted_arr = sorted(arr, reverse=True)
    return sorted_arr[k-1]
103 chars
4 lines

This function takes an array arr and a positive integer k as input, and returns the kth largest element in the array.

Example usage:

main.py
arr = [3, 5, 1, 7, 4, 9, 2]
k = 3
print(kth_largest_element(arr, k))   # output: 5
83 chars
4 lines

In this example, the input array is [3, 5, 1, 7, 4, 9, 2], and we want to find the 3rd largest element, which is 5. The function kth_largest_element returns the correct output.

gistlibby LogSnag