Python3 notes

简介: Python3 notes

Python 二分查找


二分搜索是一种在有序数组中查找某一特定元素的搜索算法。搜索过程从数组的中间元素开始,如果中间元素正好是要查找的元素,则搜索过程结束;如果某一特定元素大于或者小于中间元素,则在数组大于或小于中间元素的那一半中查找,而且跟开始一样从中间元素开始比较。如果在某一步骤数组为空,则代表找不到。这种搜索算法每一次比较都使搜索范围缩小一半。

image.png

实例 : 递归

# 返回 x 在 arr 中的索引,如果不存在返回 -1

def binarySearch (arr, l, r, x):  

 

   # 基本判断

   if r >= l:  

 

       mid = int(l + (r - l)/2)

 

       # 元素整好的中间位置

       if arr[mid] == x:  

           return mid  

       

       # 元素小于中间位置的元素,只需要再比较左边的元素

       elif arr[mid] > x:  

           return binarySearch(arr, l, mid-1, x)  

 

       # 元素大于中间位置的元素,只需要再比较右边的元素

       else:  

           return binarySearch(arr, mid+1, r, x)  

 

   else:  

       # 不存在

       return -1

 

# 测试数组

arr = [ 2, 3, 4, 10, 40 ]  

x = 10

 

# 函数调用

result = binarySearch(arr, 0, len(arr)-1, x)  

 

if result != -1:  

   print ("元素在数组中的索引为 %d" % result )

else:  

   print ("元素不在数组中")

执行以上代码输出结果为:

元素在数组中的索引为3

相关文章
|
5月前
|
Linux Apache Python
Python3 notes
Python3 notes
|
12月前
|
安全 Python
Python3 notes
Python3 notes
|
12月前
|
Python
Python3 notes
Python3 notes
|
12月前
|
Python
Python3 notes
Python3 notes
|
12月前
|
Linux Python
Python3 notes
Python3 notes
|
存储 数据可视化 API
70个注意的Python小Notes
Python读书笔记:70个注意的小Notes 作者:白宁超 2018年7月9日10:58:18 摘要:在阅读python相关书籍中,对其进行简单的笔记纪要。旨在注意一些细节问题,在今后项目中灵活运用,并对部分小notes进行代码标注。
1321 0
|
Python C语言 .NET
Python chapter 8 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78267298 ...
952 0
|
Python
Python chapter 2&3 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78243401 方法是Python对数据执行的操作。
1312 0
|
Python
Python chapter 4 learning notes
版权声明:本文为博主原创文章,原文均发表自http://www.yushuai.me。未经允许,禁止转载。 https://blog.csdn.net/davidcheungchina/article/details/78243661 1.
975 0