How to find kth smallest number in a list in Python
Overview
To find the smallest element in a list in Python, we use sorting algorithms.
Procedure and example
Through a sorting algorithm, we can sort a list and then, with the help of indexing, retrieve the element from the list. We can use any sorting algorithm. Here we’ll use the merge sort, which is a divide and conquer approach and has a time complexity of .
def merge_sort(array):if len(array) > 1:r = len(array)//2L = array[:r]M = array[r:]merge_sort(L)merge_sort(M)i = j = k = 0while i < len(L) and j < len(M):if L[i] < M[j]:array[k] = L[i]i += 1else:array[k] = M[j]j += 1k += 1while i < len(L):array[k] = L[i]i += 1k += 1while j < len(M):array[k] = M[j]j += 1k += 1return array# Return kth (k=3) smallest element from the listdef main():arr = [6, 5, 12, 10, 9, 1]arr = merge_sort(arr)k = 3print("kth (k=3) smallest element:",arr[k-1])main()