-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFirstOccuranceBS.java
39 lines (35 loc) · 1.23 KB
/
FirstOccuranceBS.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
package com.datastructure;
import java.util.Scanner;
public class FirstOccuranceBS {
public static void main(String[] args) {
Scanner s = new Scanner(System.in); //new instance and calling the input func
System.out.println("Enter the length of the array:");
int length = s.nextInt(); //defining size and getting the input
int[] array = new int[length]; // defining array of length provided
System.out.println("Enter the elements of the array:");
for (int i = 0; i < length; i++) {
array[i] = s.nextInt();
}
System.out.println("Enter the number to search:");
int target = s.nextInt();
int start = 0;
int end = array.length - 1;
int result = -1;
//firstOccurance
while (start<=end) {
int mid = (start + (end - start) / 2);
if (target == array[mid]) {
result = mid;
end = mid - 1;
// break;
}
else if (target<=array[mid])
{
end = mid -1;
}
else {start = mid +1;
}
}
System.out.println("Result found " +result);
}
}