对于一个有序序列,定义头尾,取中间值和目标值比较。
如果大了就重新以中间值的前一个作为尾继续查找,小了就以中间值的后一个作为头继续查找。
每次淘汰一半,效率较高。
package com.yc.algorithm.recursion;
/**
* 二分查找
* @author yc
*/
public class BinarySearch {
public static void main(String[] args) {
int nums[] = new int[] {1, 2, 3, 4, 5, 6, 88, 100};
int target = 5;
int value = binarySearch(nums, target);
System.out.println("循环实现 : " + value);
value = binSearch(nums, 0, nums.length , target);
System.out.println("递归实现 : " + value);
}
/**
* 循环实现
* @param nums
* @param target
* @return
*/
private static int binarySearch(int[] nums, int target) {
int head = 0;
int tail = nums.length;
int mid = (tail + head)/ 2;
while (nums[mid] != target) {
if (nums[mid] > target) {
tail = mid - 1;
} else {
head = mid + 1;
}
mid = (head + tail) / 2;
}
return mid;
}
/**
* 递归实现
* @param nums
* @param head
* @param tail
* @param target
* @return
*/
private static int binSearch(int[] nums, int head, int tail, int target) {
int mid = (head + tail) / 2;
if (nums[mid] > target) {
mid = binSearch(nums, head, mid - 1, target);
} else if (nums[mid] < target){
mid = binSearch(nums, mid + 1, tail, target);
}
return mid;
}
}
输出如下 :