forked from Gaurang2908/HacktoberFest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ArrayElementBinarySearch.java
40 lines (40 loc) · 1.01 KB
/
ArrayElementBinarySearch.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
import java.util.Arrays;
import java.util.Scanner;
public class ArrayElementPositionUsingBinarySearch {
public static int binarySearch(int array[], int key) {
int start = 0;
int end = array.length - 1;
while (start <= end)
{
int mid = (start + end) / 2;
if (key == ary[mid]) {
return mid;
}
if (key <ary[mid]) {
end = mid- 1;
} else {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter SIZE of Array");
int len = sc.nextInt();
int arry[] = new int[len];
System.out.println("Enter Array Elements ");
for (int i = 0; i < len; i++) {
arry[i] = sc.nextInt();
}
Arrays.sort(arry);
System.out.println("After sorting elements are :");
for(int a:arry)
{
System.out.println(a);
}
System.out.println("Enter key value");
int k = sc.nextInt();
System.out.println("element position is on index number is "+binarySearch(arry, k));
}
}