Search insert position of K in a sorted array | Function to find insert position of K ; Lower and upper bounds ; Traverse the search space ; If K is found ; Return insert position ; Driver Code
function find_index ( arr , n , K ) { let start = 0 ; let end = n - 1 ; while ( start <= end ) { let mid = Math . floor ( ( start + end ) / 2 ) ; if ( arr [ mid ] == K ) return mid ; else if ( arr [ mid ] < K ) start = mid + 1 ; else end = mid - 1 ; } return end + 1 ; } let arr = [ 1 , 3 , 5 , 6 ] ; let n = arr . length ; let K = 2 ; document . write ( find_index ( arr , n , K ) + " " ) ;