首页 > 编程语言 > 详细

查找----python

时间:2020-03-09 22:56:08      阅读:53      评论:0      收藏:0      [点我收藏+]
class Solution:
#顺序查找
def seq_search(self,list,num):
for i in(range(len(list))):
if list[i] == num:
return i
return -1

#二分查找
#每次能够排除掉一半的数据,查找的效率非常高,但是局限性比较大。
#必须是有序序列才可以使用二分查找。

#1、非递归算法
def binary_search_normal(self,list,num):
left=0
right = len(list)-1
mid = (left+right)//2
while left <=right:
if list[mid] > num:
right = mid-1
mid = (left+right)//2
elif list[mid] < num:
left = mid+1
mid = (left + right)//2
else:
return mid
else:
return -1

#2、递归算法
def binary_search_re(self,list,num,left,right):
if left > right: #递归结束条件
return -1
mid = (left+right)//2
if list[mid] > num:
right = mid - 1
elif list[mid] < num:
left = mid + 1
else:
return mid
return solution.binary_search_re(list, num, left, right)





if __name__ == ‘__main__‘:
list = [3,5,11,17,21,23,28,30,32,50,64,78,81,95,101]
num = 32
solution = Solution()
# result1 = solution.seq_search(list,num)
# print(result1)
list.sort()
# result2 = solution.binary_search_normal(list,num)
# print(result2)
result3 = solution.binary_search_re(list,num,0,len(list)-1)
print(result3)

查找----python

原文:https://www.cnblogs.com/turningli/p/12451896.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!