二分查找(分治算法)

分治算法:

把一个大问题分解为两个相对较小的问题,分别解决每一个小问题,对两个小问题的处理方式也一样:分解为两个更小的问题,并解决它们

这个过程一直持续下去直到达到易于求解的基值情况,就不用继续分解下去了

二分查找是分治算法的一个实例

循环二分查找

public class BinarySearch {
	private int[] data;
	
	public BinarySearch(int[] data){
		this.data = data;
	}
	
	public int search(int target){
		int min = 0;
		int max = data.length - 1;
		int n = 0;
		while(true){
			n = (min + max)/2;
			if(target > data[n])
				min = n + 1;
			if(target < data[n])
				max = n - 1;
			if(target == data[n])
				return n;
			if(max < min)
				return -1;
		}
	}
	
	public static void main(String[] args) {
		int[] ints = {1,2,7,9,25,44,66,99};
		BinarySearch bs = new BinarySearch(ints);
		System.out.println(bs.search(50));
		System.out.println(bs.search(44));
	}
}
-1
5

递归二分查找

public class BinarySearch {
	private int[] data;
	
	public BinarySearch(int[] data){
		this.data = data;
	}
	
	public int search(int target,int min,int max){
		if(min > max)
			return -1;
		int n = (min + max)/2;
		if(target > data[n])
			min = n + 1;
		if(target < data[n])
			max = n -1;
		if(target == data[n])
			return n;
		else
			return search(target,min,max);
	}
	
	public static void main(String[] args) {
		int[] ints = {1,2,7,9,25,44,66,99};
		BinarySearch bs = new BinarySearch(ints);
		System.out.println(bs.search(50,0,ints.length-1));
		System.out.println(bs.search(44,0,ints.length-1));
	}
}
-1
5

 

    原文作者:查找算法
    原文地址: https://blog.csdn.net/a19881029/article/details/23272127
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞