The java binary search

Binary search

       Binary basic idea of ​​find is: the n elements is divided into two approximately equal portions, to take a [n / 2] x-compared, if x = a [n / 2], is to find x, the algorithm suspension; if XA [ n / 2], as long as the right half of x in the search array a. binary search method is also known as a binary search, which takes full advantage of the relationship between the order of the elements, using sub-conquer strategy, available in the worst case O (log n) to complete the search task. The basic idea is :( assumed here that the array elements are arranged in the ascending order) will be divided into n elements substantially the same number of halves, take a [n / 2] x to be compared with the look, if x = a [n / 2] is to find x, the algorithm terminates; if xa [n / 2], then we as long as the right half of the array a continuing search for x.

/*
 * 使用二分查找法的前提:数列是有序的,顺序存储结构 *
 * 
 * 满足条件后采用折半的方式进行判断、查找,
 * 
 * 折半数列,拿数列下标对应的元素与查找对象比较(默认数列为升序 小-->大)
 * 个人总结:先折半,再判断,
 * 
 * 
 * 
 * 
 * 
 * 
 */

public class TwoFindWay {

	public static void main(String[] args) {
		
		int[]array =new int[] {1,5,7,9,11,20,29,99};//array.length=8
		
		Boss boss =new Boss(array);
		System.out.println(boss.find(6));

		System.out.println(boss.find(1));
		System.out.println(boss.find(99));
	}

public static class Boss{
	
	
	private int[] array;
	/*
	 * 初始化数组
	 * @param array
	*/
		public Boss(int array[]) {
			
			this.array=array;	
		}

		/*
		 * 
		 * 二分查找法的实现
		 * @param find
		 * @return
		 * 		
		*/
		public int find(int fd) {
			
			if(array==null) {//空了就返回-1
				return -1;
			}
			/*
			 * 定义开始结束下标,二分位置;
			 * @param start,end,mid;
			 * 
			 * 
			 * 
			*/
			int start=0;
			
			int end =array.length-1;
			while(start<=end) {//使用while 在二分位置开始遍历,查找满足的下标元素
				
				int mid =start+(end-start)/2;
				
				if(array[mid]==fd) {
				
					return mid;//找到了满足的下标元素返回数列 下标
					
				}else if(fd<array[mid]) {
					
					end =mid-1;//折半后 如果说比数列下标元素小,就左移一位下标,
				
				}else {
					
					start=mid+1;//反之,右移一位,
				}
					
			}
			return -1;//找不到就返回0,
		}
}

	
}

Advantages: fast,

Disadvantages: use threshold.

Published 14 original articles · won praise 0 · Views 139

Guess you like

Origin blog.csdn.net/weixin_44657829/article/details/104780579