Find the smallest and second smallest elements in an array | Python program to find smallest and second smallest elements ; Function to print first smallest and second smallest elements ; There should be atleast two elements ; If current element is smaller than first then update both first and second ; If arr [ i ] is in between first and second then update second ; Driver function to test above function
import sys NEW_LINE def print2Smallest ( arr ) : NEW_LINE INDENT arr_size = len ( arr ) NEW_LINE if arr_size < 2 : NEW_LINE INDENT print " Invalid ▁ Input " NEW_LINE return NEW_LINE DEDENT first = second = sys . maxint NEW_LINE for i in range ( 0 , arr_size ) : NEW_LINE INDENT if arr [ i ] < first : NEW_LINE INDENT second = first NEW_LINE first = arr [ i ] NEW_LINE DEDENT elif ( arr [ i ] < second and arr [ i ] != first ) : NEW_LINE INDENT second = arr [ i ] ; NEW_LINE DEDENT DEDENT if ( second == sys . maxint ) : NEW_LINE INDENT print " No ▁ second ▁ smallest ▁ element " NEW_LINE DEDENT else : NEW_LINE INDENT print ' The ▁ smallest ▁ element ▁ is ' , first , ' and ' ' ▁ second ▁ smallest ▁ element ▁ is ' , second NEW_LINE DEDENT DEDENT arr = [ 12 , 13 , 1 , 10 , 34 , 1 ] NEW_LINE print2Smallest ( arr ) NEW_LINE