Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize binary search in Python

2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

In this issue, Xiaobian will bring you about how to achieve binary search in Python. The article is rich in content and analyzes and narrates from a professional perspective. After reading this article, I hope you can gain something.

binary search

Binary search: compare from the middle of the list

If the middle item in the list happens to be the target item, the search ends and returns True.

If the middle item> target item: it can only appear in the first half

If the middle term

< 目标项:则只可能出现在后半部分 故每一次比对之后,都会将目标项所在范围缩小为原来的一般 : n/2 注意:有序表才能使用二分查找法

Divide and conquer

The binary search algorithm actually embodies a strategy for solving problems: divide and conquer.

Divide the original problem into smaller problems, and the solution of each small problem is the solution of the original problem.

Another divide-and-conquer algorithm is recursion.

Recursion can also be used to achieve binary search, the basic end condition is that the list length is 0

Analysis of Binary Search Algorithm

Because each binary search reduces the range of the next match by half

Comparisons Number of remaining data items

1

n/2

2

n/4

3n/8……

……

i

n/2^i

The above is how to achieve binary search in Python shared by Xiaobian. If there is a similar doubt, please refer to the above analysis for understanding. If you want to know more about it, please pay attention to the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 229

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report