K Smallest Elements In List
Question
Write an efficient program for printing k largest elements in an array. Elements in array can be in any order.
For example, if given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30 and 23.
Solution
- Sort the elements in descending order in O(nLogn)
- Print the first k numbers of the sorted array O(k).
Code
def k_smallest(arr, k):
arr.sort()
for i in range(k): print (arr[i], end =" ")
arr = [1, 23, 12, 9, 30, 2, 50]
k = 3
k_smallest(arr, k)