首页 > 解决方案 > 根据最大值(最后一项)、最小值(第一项)和使用二分搜索的搜索值估计要搜索的项的位置

问题描述

我的代码:

    def binary_search(seq,item):
    """It uses non recursive method to search the item in the given seq. 
       It returns the position of item if found, None otherwise"""

    left_index=0
    right_index=len(seq)-1
    while left_index <= right_index:            #stop searching when left_index >   right_indext
    mid_index=(right_index + left_index)//2 #find the mid point
    if seq[mid_index]==item:
    return mid_index
    elif seq[mid_index]>item:
    right_index = mid_index -1          #if mid point ele > search ele, move right pointer
    else:  
    left_index = mid_index + 1        #if mid point ele < search ele, move left pointer
    return None
    a=[1,2,3,4,5,6,7,8,9]
    print(binary_search(a,6))
Output: "5"

如何改进上面的代码?

我想item根据max value(最后一项)、min value(第一项)和search value. 我上面的代码正在使用中间的list搜索,这将需要更长的时间才能到达。

谁能告诉我在哪里可以更改我的代码并进一步改进它?

标签: pythondata-structuresbinary-search

解决方案


推荐阅读