-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.java
More file actions
53 lines (46 loc) · 1.38 KB
/
Copy pathBinarySearch.java
File metadata and controls
53 lines (46 loc) · 1.38 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
/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static int binarySearchIter(int[] arr, int start, int end, int target) {
while(start < end) {
int mid = (start + end)/2;
if(arr[mid] == target)
return mid;
else if(arr[mid] > target)
end = mid-1;
else
start = mid+1;
}
if(arr[start] == target)
return start;
else
return -1;
}
public static int binarySearchRecur(int[] arr, int start, int end, int target) {
if(start <= end) {
int mid = (start+end)/2;
if(arr[mid] == target) {
return mid;
} else if(arr[mid] > target) {
return binarySearchRecur(arr, start, mid-1, target);
} else {
return binarySearchRecur(arr, mid+1, end, target);
}
}
return -1;
}
public static void main (String[] args) throws java.lang.Exception
{
int[] arr = {10, 20, 30, 50, 70, 90, 110};
System.out.println(binarySearchIter(arr, 0, arr.length-1, 70));
System.out.println(binarySearchRecur(arr, 0, arr.length-1, 70));
System.out.println(binarySearchIter(arr, 0, arr.length-1, 60));
System.out.println(binarySearchRecur(arr, 0, arr.length-1, 60));
System.out.println(binarySearchIter(arr, 0, arr.length-1, 30));
System.out.println(binarySearchRecur(arr, 0, arr.length-1, 30));
}
}