forked from 790hanu/Annex-qr-code-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BinarySearch.java
47 lines (44 loc) · 1.36 KB
/
BinarySearch.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
package com.TrX;
//Program on BinarySearch #Day1of100DaysOfCoding
public class BinarySearch {
public static void main(String[] args) {
int[] arr1 = {1, 2, 4, 5, 6, 7, 8, 9};
int key = 8;
int last = arr1.length - 1;
binarySearch(arr1, 0, last, key);
}
// public static void binarySearch(int[] arr, int first, int last, int key) {
// int mid = (first+last)/2;
// while(first<=last){
// if(arr[mid]==key){
// System.out.println("Element found at index :"+mid);
// break;
// }
// else if(arr[mid]<key){
// first=mid+1;
// }
// else{
// last=mid-1;
// }
// mid=(first+last)/2;
// }
public static void binarySearch(int[] arr, int first, int last, int key) {
int mid = (first+last)/2;
while(first<=last){
if(arr[mid]==key){
System.out.println("Element found at index :"+mid);
break;
}
else if(arr[mid]<key){
first=mid+1;
}
else{
last=mid-1;
}
mid=(first+last)/2;
}
if(first>last){
System.out.println("Element not Found");
}
}
}