Find index of first occurrence when an unsorted array is sorted | Java 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 java . util . * ; class GFG { static int findFirst ( int arr [ ] , int n , int x ) { Arrays . sort ( arr ) ; int ptr = lowerBound ( arr , 0 , n , x ) ; return ( arr [ ptr ] != x ) ? - 1 : ( ptr ) ; } static int lowerBound ( int [ ] a , int low , int high , int element ) { while ( low < high ) { int middle = low + ( high - low ) / 2 ; if ( element > a [ middle ] ) low = middle + 1 ; else high = middle ; } return low ; } public static void main ( String [ ] args ) { int x = 20 , arr [ ] = { 10 , 30 , 20 , 50 , 20 } ; int n = arr . length ; System . out . println ( findFirst ( arr , n , x ) ) ; } }