-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy path_7.BinarySort.java
More file actions
56 lines (36 loc) · 1.15 KB
/
_7.BinarySort.java
File metadata and controls
56 lines (36 loc) · 1.15 KB
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
import java.util.*;
public class BinarySort {
public static void main(String args[]) {
int num, i = 0;
System.out.println("Enter The Number Of Elements: ");
Scanner sc = new Scanner(System.in);
num = sc.nextInt();
System.out.println("Enter The Elements (Ascending order): ");
int arr[] = new int[num];
while (i < num) {
arr[i] = sc.nextInt();
i++;
}
System.out.println("Enter The element To Search: ");
int sr = sc.nextInt();
int l = 0, r = num - 1;
int mid = 0;
while (l <= r) {
mid = (l + r) / 2;
if (arr[mid] == sr) {
break;
} else if (arr[mid] > sr) {
r = mid - 1;
continue;
} else {
l = mid + 1;
continue;
}
}
if (l > r) {
System.out.println("Elements Not Found ! ");
} else if (arr[mid] == sr) {
System.out.println(arr[mid] + " Found At Position " + mid);
}
}
}