-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathBinarySearchArray.java
More file actions
92 lines (70 loc) · 2.29 KB
/
BinarySearchArray.java
File metadata and controls
92 lines (70 loc) · 2.29 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package dataStructures.arrays;
/**
* Binary search algorithm
* @author meugenom
*/
public class BinarySearchArray {
/**
* iterative method
* @param nums - sorted array @param target - number to search @return index of
* @return -1 if number is not present in the array or array is empty
* @complexity time O(log n)
* @complexity space O(1)
*/
public int searchIterative(int[] nums, int target) {
int low = 0;
int high = nums.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (nums[mid] == target) {
return mid; // searched number found ... got to the end
} else if (nums[mid] < target) {
low = mid + 1; // in the next iteration we use right part of the array
} else {
high = mid - 1; // in the next iteration we use left part of the array
}
}
return -1;
}
/**
* recursive method
* @param nums - sorted array @param target - number to search @param low - index
* of the first element in the array @param high - index of the last element in
* the array @return index of @return -1 if number is not present in the array or
* array is empty
* @complexity time O(log n)
* @complexity space O(log n)
*/
public int searchRecursive(int[] nums, int target, int low, int high) {
if (low == high || low > high) //if number is not present in the array or array is empty
return -1;
if (nums[low] == target)
return low;
if (nums[high] == target)
return high;
int mid = (high + low) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] > target) {
high = mid - 1;
return searchRecursive(nums, target, low, high);
} else {
low = mid + 1;
return searchRecursive(nums, target, low, high);
}
}
public static void main(String[] args) {
//first example
int[] nums = new int[] { 1, 4, 7, 15, 67, 89, 90, 234, 678, 876, 901, 1020 };
int target = 234;
BinarySearchArray bs = new BinarySearchArray();
int res = bs.searchRecursive(nums, target, 0, nums.length - 1);
System.out.println("result = " + res);
//second example
int[] nums1 = new int[] { 1, 2, 11, 15, 49, 71, 94, 134, 278, 476, 501, 720 };
int target1 = 11;
BinarySearchArray bs1 = new BinarySearchArray();
int res1 = bs1.searchRecursive(nums1, target1, 0, nums1.length - 1);
System.out.println("result = " + res1);
}
}