算法:当数据量很大适宜采用该方法。采用二分法查找时,数据需是有序不重复的。 基本思想:假设数据是按升序排序的,对于给定值 x,从序列的中间位置开始比较,如果当前位置值等于 x,则查找成功;若 x 小于当前位置值,则在数列的前半段中查找;若 x 大于当前位置值则在数列的后半段中继续查找,直到找到为止。

假设有一个数组 { 1,2,3,4,5,6,7,8,9,10 },现要求采用二分法找出指定的数值并将其在数组的索引返回,如果没有找到则返回 -1。代码如下:

public class DichotomySearch {
	
	
	public static void main(String[] args) {
		int [] a={1,2,3,4,5,6,7,8,9,10};
		 System.out.println(dichotomy(a, 12));
	}
	
	public  static int dichotomy(int [] a,int key){
		int start =0;
		int end=a.length-1;
	while(start<=end){
		int middle=(start+end)/2;
		if(key<a[middle]){
			end=middle-1;
			
		}else if(key>a[middle]){
			start=middle+1;
		}else {
			return middle;
		}
	}
	
	return -1;
	}

}

  

相关文章:

  • 2021-10-12
  • 2021-12-01
  • 2021-08-02
  • 2021-09-09
  • 2021-10-09
  • 2022-12-23
  • 2021-08-31
  • 2021-11-20
猜你喜欢
  • 2021-12-11
  • 2021-09-12
  • 2021-06-22
  • 2022-02-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案