Find index of first occurrence when an unsorted array is sorted | Python3 program to find index of first occurrence of x when array is sorted . ; lower_bound returns iterator pointing to first element that does not compare less to x . ; If x is not present return - 1. ;  ; Driver Code
import math NEW_LINE def findFirst ( arr , n , x ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ptr = lowerBound ( arr , 0 , n , x ) NEW_LINE return 1 if ( ptr != x ) else ( ptr - arr ) NEW_LINE DEDENT def lowerBound ( a , low , high , element ) : NEW_LINE INDENT while ( low < high ) : NEW_LINE INDENT middle = low + ( high - low ) // 2 NEW_LINE if ( element > a [ middle ] ) : NEW_LINE INDENT low = middle + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = middle NEW_LINE DEDENT DEDENT return low NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT x = 20 NEW_LINE arr = [ 10 , 30 , 20 , 50 , 20 ] NEW_LINE n = len ( arr ) NEW_LINE print ( findFirst ( arr , n , x ) ) NEW_LINE DEDENT