Find kth largest element in an array Python
Here you will learn the program code to find kth largest element in an array using python programming.
The “kth element” in an array is the element placed at the location indicated by the value of ‘k’.
Example to find kth largest element in an array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | def kth_largest(arr, k): # Sort array in descending order arr.sort(reverse=True) # Return kth largest element return arr[k - 1] # sample array array_list = [12, 45, 23, 67, 89, 34, 90] # find value of k (kth largest) k = int(input("Enter a Number : ")) # Find and print the kth largest result = kth_largest(array_list, k) print(f"The {k}th largest element is:", result) |
Output
Enter a Number : 2
The 2th largest element is: 89
Check out our other Python Examples