# Example analysis of Python binary search algorithm

Source: Internet
Author: User

This article mainly introduces the Python binary search algorithm, examples of Python to achieve the binary method of the relevant skills, with a certain reference value, the need for friends can refer to the

Reading today, the book mentions that the two-point method although the reason is simple, we listen to understand but really can write a one-time error of the implementation is still more difficult, even if you have enough time, such as 1 hours. If you are not particularly serious, you may still have some such mistakes, so try to do it yourself to see whether the passage, the results naturally self-evident, although the use of time is not long, but I failed, hehe.

Personally feel that the main reason for failure is that they do not seriously think of this idea and the possible branch of the situation, but directly to the subjective assumption to write code, completely in the book said behavior, so also as the book said, a mistake. After debugging should be to get the basic correct algorithm, the contents are as follows:

?

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 The 25 26 #!/usr/bin/env python #encoding: Utf-8 def half_search (Search_arr, search_str): lb = 0 ub = Len (Search_arr)-1 for I in R Ange (UB/2 + 1): If lb > ub:return-1 mid = (UB + lb)/2 if search_arr[mid] = = Search_str:return Mid elif Search_arr[mi D] > search_str:ub = mid-1 else:lb = mid + 1 if __name__== ' __main__ ': arr = [10,20,30,40,50,60,70] Print Half_searc H (arr, 1) Print half_search (arr, one) print Half_search (arr,) print Half_search (arr,) print Half_search (arr,) prin T Half_search (arr) print Half_search (arr, \$) Print half_search (arr,) print Half_search (arr, 8)

Results:

?

 1 2 3 4 5 6 7 8 9 -1-1-1-1 3-1-1 6-1

The positive integer represents the subscript in the array, 3 that is the 4th position;-1 means No.

Summarize:

Before implementing a simple algorithm, if you already have a set of easiest implementations "such as printing 100 similar content directly", think about whether there is a more sophisticated implementation of "can use cyclic + parametric substitution", to achieve a slightly more complex point of the algorithm, you may wish to draw on the paper a variety of possible validation, Avoid the realization of the lack of arms and short legs, there is a point is the algorithm or something to practice, or slightly more complex after a while may forget the details. I think this is called the surgery industry has a specialization!

Related Keywords:
Related Article

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD