Python3 二分查找和线性查找

$ 二分查找(参考:菜鸟教程 https://www.runoob.com/python3/python-binary-search.html

# 返回 x 在 arr 中的索引,如果不存在返回 -1
def binarySearch (arr, left_v, right_v, x): 
  
    # 基本判断
    if right_v >= left_v: 
  
        mid = int((right_v + left_v)/2)
  
        # 元素整好的中间位置
        if arr[mid] == x: 
            return mid 
          
        # 元素小于中间位置的元素,只需要再比较左边的元素
        elif arr[mid] > x: 
            return binarySearch(arr, left_v, mid-1, x) 
  
        # 元素大于中间位置的元素,只需要再比较右边的元素
        else: 
            return binarySearch(arr, mid+1, right_v, x) 
  
    else: 
        # 不存在
        return -1
  
# 输入列表
arr = []
while True:
    ele = input("Please input an int value(input 'end' to finish):")
    if ele == 'end':
        break
    else:
        try:
            int(ele)
        except ValueError:
            print("Please input a number!")
            continue
        ele = int(ele)
        arr.append(ele)

        if len(arr)>1 and arr[(len(arr)-2)] > ele:
            arr.pop()
            print("The input value should not smaller than the previous one!")
    
print("The array is:",arr)
#arr = [ 2, 3, 4, 10, 40 ] 

while True:
    x = input("Please input an int value to find in the array:")
    try:
        x = int(x)
        # 函数调用
    except ValueError:
        print("Please input a number!")
        continue
    
    result = binarySearch(arr, 0, len(arr)-1, x) 
    if result != -1: 
        print ("元素在数组中的索引为 %d" % result )
    else: 
        print ("元素不在数组中")
    break
  

 

$ 线性查找(参考:菜鸟教程 https://www.runoob.com/python3/python-linear-search.html

def search(arr, x): 
  
    for i in range (len(arr)): 
        if (arr[i] == x): 
            return i; 
    return -1; 
  
# 输入列表
arr = []
while True:
    ele = input("Please input an int value(input 'end' to finish):")
    if ele == 'end':
        break
    else:
        try:
            int(ele)
        except ValueError:
            print("Please input a number!")
            continue
        ele = int(ele)
        arr.append(ele)

        if len(arr)>1 and arr[(len(arr)-2)] > ele:
            arr.pop()
            print("The input value should not smaller than the previous one!")
    
print("The array is:",arr)
#arr = [ 2, 3, 4, 10, 40 ] 

while True:
    x = input("Please input an int value to find in the array:")
    try:
        x = int(x)
        # 函数调用
    except ValueError:
        print("Please input a number!")
        continue
    
    result = search(arr, x) 
    if(result == -1): 
        print("元素不在数组中") 
    else: 
        print("元素在数组中的索引为", result);
    break
  

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值