二进制搜索2列表

时间:2015-08-19 08:39:28

标签: python list python-3.x binary-search

我只是想知道是否有更好的方法来实现二进制搜索而不是我的代码?我的功能是两个列表 - first_booth_voters和second_booth_voters,其中second_booth_voters正在排序,first_booth_voters未排序。我觉得我正在进行不必要的比较。干杯

from classes import VoterList
def fraud_detect_bin(first_booth_voters, second_booth_voters):

fraud = VoterList()
comparisons = 0

for i in range(0, len(first_booth_voters)):
    item = first_booth_voters[i]
    first = 0
    last = len(first_booth_voters) - 1

    while first <= last:
        midpoint = (first + last) // 2

        if second_booth_voters[midpoint] == item:
            comparisons += 1
            fraud.append(second_booth_voters[midpoint])
            break 
        else:
            if item < second_booth_voters[midpoint]:
                last = midpoint - 1
                comparisons += 2
            else:
                first = midpoint + 1
                comparisons += 2

return fraud, comparisons

0 个答案:

没有答案