Python Program to Select the nth Largest Element from a List in Expected Linear Time

PythonServer Side ProgrammingProgramming

When it is required to select the nth largest element from a list in linear time complexity, two methods are required. One method to find the largest element, and another method that divides the list into two parts. This division depends on the ‘i’ value that is given by user. Based on this value, the list is split, and the largest element is determined.

Below is a demonstration of the same −

Example

 Live Demo

def select_largest(my_list, beg, end, i):
   if end - beg <= 1:
      return my_list[beg]
   pivot_val = start_partition(my_list, beg, end)

   k = end - pivot_val

   if i < k:
      return select_largest(my_list, pivot_val + 1, end, i)
   elif i > k:
      return select_largest(my_list, beg, pivot_val, i - k)

   return my_list[pivot_val]

def start_partition(my_list, beg, end):
   pivot_val = my_list[beg]
   i = beg + 1
   j = end - 1

   while True:
      while (i <= j and my_list[i] <= pivot_val):
         i = i + 1
      while (i <= j and my_list[j] >= pivot_val):
         j = j - 1

      if i <= j:
         my_list[i], my_list[j] = my_list[j], my_list[i]
      else:
         my_list[beg], my_list[j] = my_list[j], my_list[beg]
         return j

my_list = input('Enter the list of numbers.. ')
my_list = my_list.split()
my_list = [int(x) for x in my_list]
i = int(input('Enter the value for i.. '))

ith_largest = select_largest(my_list, 0, len(my_list), i)
print('The result is {}.'.format(ith_largest))

Output

Enter the list of numbers.. 34 67 12 0 999
Enter the value for i.. 1
The result is 999.

Explanation

  • A method named ‘select_largest’ is defined, that takes the list, the beginning, end and an ‘i’ value is taken as parameter.

  • Another method named ‘start_partition’ is defined that divides the list into two parts depending on the value of ‘i’.

  • This method is called in the ‘select_largest’ method.

  • The ‘select_largest’ is also called again inside the same function- this is how recursion works.

  • The numbers are taken as input from the user.

  • It is split based on default value.

  • It is iterated over.

  • A value for ‘i’ is taken from the user.

  • Based on this ‘i’ value, the list is divided into two parts.

  • The ‘select_largest’ method is called on one of the lists.

  • The output is displayed on the console.

raja
Published on 15-Apr-2021 12:38:09
Advertisements