text: Print n smallest elements from given array in their original order | Function for binary_search ; Function to print smallest n numbers ; Make copy of array ; Sort copy array ; For each arr [ i ] find whether it is a part of n - smallest with binary search ; Driver Code
code: def binary_search ( arr , low , high , ele ) : NEW_LINE INDENT while low < high : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE if arr [ mid ] == ele : NEW_LINE INDENT return mid NEW_LINE DEDENT elif arr [ mid ] > ele : NEW_LINE INDENT high = mid NEW_LINE DEDENT else : NEW_LINE INDENT low = mid + 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT def printSmall ( arr , asize , n ) : NEW_LINE INDENT copy_arr = arr . copy ( ) NEW_LINE copy_arr . sort ( ) NEW_LINE for i in range ( asize ) : NEW_LINE INDENT if binary_search ( copy_arr , low = 0 , high = n , ele = arr [ i ] ) > - 1 : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE asize = len ( arr ) NEW_LINE n = 5 NEW_LINE printSmall ( arr , asize , n ) NEW_LINE DEDENT