Find the “Kth” max and min element of an array

find kth smallest and largest element using python

“Kth” max and min element in Python

In this article we will see a python program to find kth max and min element of an array. User will enter array and value of k. And then compiler will give output of k th smallest and k th largest element.

Let’s consider an example:

  • array=  [1, 7, 6, 8, 9, 2, 4, 5, 3, 0] k = 2
  • kth largest element: 8
  • kth smallest element: 1

Algorithm

  • Step 1: Call findkmax and findkmin and pass array and value of k.

Algorithm for Function findkmax

  • Step 1: Sort the array in descending order using predefined function sort
  • Step 2: print array[k-1] after sorting the array in descending order

Algorithm for Function findkmin

  • Step 1: Sort the array in ascending order using predefined function sort
  • Step 2: print array[k-1] after sorting the array in ascending order
python program to find kth max and min element

Python code

Run
def findkmax(k, array):
    # sort the array in descending order
    array.sort(reverse=True)

    # Since indexing start from 0, hence if user want first number, that means index=0
    print("K th maximum element is: ", array[k - 1])


def findkmin(k, array):
    # sort the array in ascending order
    array.sort()

    # Since indexing start from 0, hence if user want first number, that means index=0
    print("K th minimum element is: ", array[k - 1])


array = [1, 7, 6, 8, 9, 2, 4, 5, 3, 0]
k = 2

# call function findkmax
findkmax(k, array)

# call function findkmin
findkmin(k, array)

Output

K th maximum element is: 8
K th minimum element is: 1

Optimal solution (Python Code)

Run
def find(k, arr, l):
    # sort the array in descending order
    arr.sort(reverse=True)

    # Since indexing start from 0, hence if user want first number, that means index=0
    print("K th maximum element is: ", arr[k - 1])

    # Since the array is sort in reverse order for minimum we have to find from end
    print("K th minimum element is: ", array[l - k])


array = [1, 7, 6, 8, 9, 2, 4, 5, 3, 0]
k = 2
# call function
find(k, array, len(array))

Output

K th maximum element is: 8
K th minimum element is: 1

For similar question click on the given button

Comments