Skip to content

Commit 03f5ad2

Browse files
Add files via upload
1 parent 14b9d66 commit 03f5ad2

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

binary_search.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.Scanner;
2+
class binary_search {
3+
public static void main(String[] args) {
4+
int arr[] = {2,4,5,7,6,9,12,15,18};
5+
int first, mid, last;
6+
System.out.println("Given array element:");
7+
for (int i=0; i<arr.length ;i++ ) {
8+
System.out.print(arr[i]+" ");
9+
}
10+
System.out.println("\n====================");
11+
Scanner scn = new Scanner(System.in);
12+
System.out.print("Enter the element to search:");
13+
int search = scn.nextInt(); first = 0;
14+
last = arr.length-1; mid = (first+last)/2;
15+
while (first <= last){
16+
if (arr[mid] < search) {
17+
first = mid + 1;
18+
}
19+
else if (arr[mid] == search) {
20+
System.out.println(search+" is found at location: "+ (mid+1)); break;
21+
}
22+
else {
23+
last = mid - 1;
24+
}
25+
mid = (first + last) /2;
26+
}
27+
if (first > last) {
28+
System.out.println("Element is not found");
29+
}
30+
}
31+
}
32+

0 commit comments

Comments
 (0)