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

PythonServer Side ProgrammingProgramming

When it is required to select the nth smallest element from a list in linear time complexity, two methods are required. One method to find the smallest 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 smallest element is determined.

Below is a demonstration of the same −

Example

 Live Demo

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

   k = pivot_val - beg + 1

   if i < k:
      return select_smallest(my_list, beg, pivot_val, i)
   elif i > k:
      return select_smallest(my_list, pivot_val + 1, end, 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_smallest = select_smallest(my_list, 0, len(my_list), i)
print('The result is {}.'.format(ith_smallest))

Output

Enter the list of numbers.. 43 12 67 89 99 0
Enter the value for i.. 3
The result is 43.

Explanation

  • A method named ‘select_smallest’ 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_smallest’ method.

  • The ‘select_smallest’ 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_smallest’ method is called on one of the lists.

  • The output is displayed on the console.

raja
Published on 14-Apr-2021 14:18:43
Advertisements