Hand line and binary search

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

title: Hand line and binary search
DATE: 2019-04-20 23:15:55
Tags: binary search
categories: Algorithms

Hand line and binary search

Here is their own understanding of binary search for future review:

  • Find a binary premise: the content is ordered
	public static void main(String[] args) {
		int[] arry = new int[] { 1, 8, 10, 50, 60, 80 };
		
		//设置一个标记
		boolean flag=true;
		
		//目标值
		int target = 10;
		
		//头结点
		int head = 0;
		
		//尾结点
		int end = arry.length - 1;
		
		//头结点与尾结点相同的时候查找结束
		while (head <= end) {
			
			//中间结点
			int middle = (head + end) / 2;
			if (target == arry[middle]) {
				System.out.println("位置为" + middle);
		
        		//如果查找成功,标记点为false
				flag=false;
				
				//查找成功,跳出循环标记为false
				break;
				
				//查找值小于中间结点值
			} else if (arry[middle] > target) {
			
				//中间结点减一为尾结点
				end = middle - 1;
				
				//查找值大于中间结点值
			} else {
			
				//中间结点加为头结点
				head = middle + 1;
			}
		}
		
		//标记点为alse就不会显示查找失败
		if(flag) {
			System.out.println("没有找到");
		}
	}

Guess you like

Origin blog.csdn.net/qq_39943682/article/details/93472247