二分查找(Binary Search)

Posted by 余腾 on 2019-02-24
Estimated Reading Time 1 Minutes
Words 242 In Total
Viewed Times

二分查找

必须在有序数组中查找

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
public class BinarySearch {

public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11, 23, 56, 89, 119, 2223, 3333, 656556};

int index = binarySearch(arr, 2);
System.out.println(index);
}


public static int binarySearch(int[] arr, int item) {

int low = 0;
int high = arr.length - 1;
int index = -1;

while (low <= high) {

int mid = (low + high) / 2;
int guess = arr[mid];

if (guess == item) {
index = mid;
break;
}
if (guess > item) {
high = mid - 1;
}
if (guess < item) {
low = mid + 1;
}
}
return index;
}
}

递归折半查找

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
public class RecursiveBinarySearch {

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 23, 56, 89, 119, 2223, 3333, 656556};

int index = binarySearch(arr, -2, 0, arr.length - 1);
System.out.println(index);
}

private static int binarySearch(int[] arr, int item, int low, int high) {

if (low > high) {
return -1;
}
int mid = (low + high) / 2;
int guess = arr[mid];

if (guess == item) {
return mid;
} else if (guess > item) {
return binarySearch(arr, item, low, mid - 1);
} else {
return binarySearch(arr, item, mid + 1, high);
}
}
}

感谢阅读


If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !