Skip to content

Instantly share code, notes, and snippets.

@mkamranhamid
Last active December 15, 2019 09:37
Show Gist options
  • Save mkamranhamid/dc9ce19c622a5b083484c47f01477a77 to your computer and use it in GitHub Desktop.
Save mkamranhamid/dc9ce19c622a5b083484c47f01477a77 to your computer and use it in GitHub Desktop.
a function to get the K'th largest value in python
# For an unsorted array/list of n integers find the k-th largest element, where k <= n-1.
# Example: For A = [5,9,27,3,28,18,45] and k=4 the output will be 18.
def findKthLargestNumber(arr, n=3):
k= n-1 #
print(arr) # previous state
arr.sort(reverse=True) # {reverse=True} will make the sort to work in descending order
print(arr) # after sort in descending order
print(arr[k]) # fetch the kth value
findKthLargestNumber([5,9,27,3,28,18,45] ,4)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment