数组/列表中的多个二进制搜索

问题描述

这是执行二进制搜索的常用程序

def binary_search(lst,num):
    fl=0
    low=0
    high=len(lst)
    while low<=high :
        mid=int((low+high)/2)
        if lst[mid]==num :
            fl=1
            print ('Number Found at index:',mid)
            break
        elif lst[mid]>num :
            low=mid+1
        else :
            high=mid-1
    if fl==0 :
        print ('Number Not Found')
lst=eval(input("Enter a sorted list:")
num=int(input("Enter a number to find:")
binary_search(lst,num)

问题
如果元素要在列表/数组中出现1次以上,我想搜索并打印该元素的索引怎么办
示例:列表= [1,1,2,3,4,5]
我想搜索1,它出现3次,所以我想打印所有3个索引,例如:-

在索引处找到编号:0
在索引处找到的数字:1
在索引处找到的数字:2

(二进制搜索为必填项)

解决方法

此代码应满足您的要求:

def binary_search(lst,num):
    element_found = False
    low = 0
    high = len(lst)
    while low <= high:
        mid = (low + high) // 2
        if lst[mid] == num:
            # Here you have found your element. If the list has several times this values,it will be the neighbours
            element_found = True
            find_equal_neighbours(lst,mid)
            break
        elif lst[mid] < num:
            low = mid + 1
        else:
            high = mid - 1
    if not element_found:
        print('Number Not Found')


def find_equal_neighbours(lst,index):
    low_index = index
    high_index = index
    value = lst[index]
    while low_index - 1 >= 0 and lst[low_index - 1] == value:
        low_index -= 1
    while high_index + 1 < len(lst) and lst[high_index + 1] == value:
        high_index += 1
    for i in range(low_index,high_index + 1):
        print('Number Found at index:',i)


lst = [1,1,3,4,5]
num = 1
binary_search(lst,num)

在二元搜索中找到所需的元素后,如果列表中的其他元素具有相同的值,则它们将排在您的元素旁边(因为这是一个排序列表)。 函数find_equal_neigbours(lst,index)打印与列表index中索引lst上的元素相等的neigbhours值的所有索引。

它打印:

Number Found at index: 0
Number Found at index: 1
Number Found at index: 2