Binary search algorithm analysis and summary

How it works: you think you're doing guessing game, 1-100, you need to guess the number, you will first take 50 to ask him right, if that is the end of the 50 game; if the guess is big, then you certainly will not be between 50-100 guess, but to shrink the interval between 1-49 (both inclusive) continue to guess, you will continue to take the middle value of the right to ask him to make the interval depending on the size control, and so gradually shrink that number will be able to know specifically how much. When returns the result? That you find this number, or a range shrinks to 0 can not be contracted (looking over but could not find).

Of course, no two points, then you most stupid way is to ask him one by one right, asked from 1 to 100, the worst case you need to guess 100 times ... reflected in the Code is the order of traversal.

Conditions: an ordered set of data

Bipartite realization (caveats are in comments)

func search2(arr []int, low, high, num int) int {

	// 缩小区间最后会出现[12,12]的情况,因此循环的条件不能是low < high,而是low <= high,
	// 当然如果你开始传入的high本身就是len(arr)而非len(arr)-1,那此处就可以low < high
	for low <= high {
		midIndex := (low + high) / 2
		//fmt.Println("low=", low, "   high=", high, "   mid=", midIndex)
		if arr[midIndex] == num { // 如果最中间的值就是要找的数,直接返回索引
			return midIndex
		} else if num < arr[midIndex] {
			high = midIndex - 1
		} else if num > arr[midIndex] { 
			low = midIndex + 1 // 移动区间端点进行缩小区间
		}
	}

	return -1
}

It can be seen part of each execution is the same logic can also be implemented using recursion:

func search3(arr []int, low, high, num int) int {
	if low > high { // 没找到时递归结束
		return -1
	}

	midIndex := (low + high) / 2
	if arr[midIndex] == num {
		return midIndex
	} else if num < arr[midIndex] {
		high = midIndex - 1
	} else if num > arr[midIndex] {
		low = midIndex + 1
	}

	return search3(arr, low, high, num)
}

First write, finished continue to add ~

 

 

He published 182 original articles · won praise 132 · views 90000 +

Guess you like

Origin blog.csdn.net/HYZX_9987/article/details/104800013