-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLowerBound.java
64 lines (50 loc) · 1.56 KB
/
LowerBound.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// Modification of Binary Search
// Time Complexity: O(log n)
// Space Complexity: O(1)
import java.io.*;
import java.util.*;
class LowerBound {
// function definition
public static int findFirstOccurence(int[] arr, int target){
int low=0, high=arr.length-1;
int result = -1;
while(low <= high){
//to avoid overflow
int mid = low + (high - low)/2;
if(arr[mid] == target){
result = mid;
// traverse to the left side of an array
high = mid - 1;
}
else if(arr[mid] > target){
high = mid - 1;
}
else{
low = mid + 1;
}
}
return result;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of elements in an array: ");
int n = sc.nextInt();
int arr[] = new int[n];
System.out.println("Enter the array elements: ");
for(int i=0; i<n; i++){
arr[i] = sc.nextInt();
}
System.out.println("Enter the target element:");
int target = sc.nextInt();
// function calling
int result = findFirstOccurence(arr, target);
if(result == -1){
System.out.println("Target element is not present in an array");
}
else{
System.out.println("Target element first occurence is present at index: "+result);
}
}
}
LowerBound.java
Displaying LowerBound.java.