二分查找
作者:互联网
二分查找
# -*- coding: utf-8 -*-
# @Time : 2022/3/28 15:20
# @Author : chuqianyu
# @FileName: 二分查找2.py
# @Software: PyCharm
# @Blog :https://home.cnblogs.com/u/chuqianyu
class Solution:
def search(self, nums: list, target: int) -> int:
# write code here
# binarySearch
kk = Solution.binarySearch(self, nums, 0, len(nums) - 1, target)
return kk
# 暴力求解
# for i in range(len(nums)):
# if target == nums[i]:
# return i
# else:
# return -1
# binarySearch
def binarySearch(self, arr, m, n, x): # m,n为下标,所以n = len(arr)-1
if n >= m:
mid = m + ((n - m) >>1) # 等效为 mid = int(m + (n-m)/2) #int为向下取整
if arr[mid] == x:
return mid
elif arr[mid] > x:
return Solution.binarySearch(self, arr, m, mid - 1, x)
else:
return Solution.binarySearch(self, arr, mid + 1, n, x)
else:
return -1
if __name__ == "__main__":
print(int(3.5)) # 3向下取整
s = Solution()
x = int(input()) # 输入要查找的数
arr = list(map(int, input().strip().split())) # 有序数组
m = 0
n = len(arr) - 1
index = s.search(arr, x)
if index != -1:
print("元素在数组中的索引为 %d" % index)
else:
print("元素不在数组中")
标签:二分,arr,return,int,self,mid,binarySearch,查找 来源: https://www.cnblogs.com/chuqianyu/p/16247769.html