二进制搜索算法不起作用

时间:2016-12-01 02:32:08

标签: python algorithm binary-search

所以我编写了一个二进制搜索算法,但是当我进行测试运行时,它并不能很好地工作。

这是代码

val ys = Map("a" -> List(1 -> 11,1 -> 111), "b" -> List(2 -> 22,2 -> 222)).flatMap(e => {
     |    println("e =" + e)
     |    (e._2)
     | })
e =(a,List((1,11), (1,111)))
e =(b,List((2,22), (2,222)))
ys: scala.collection.immutable.Map[Int,Int] = Map(1 -> 111, 2 -> 222)

abd这里是调用函​​数的代码

def binarySearch(lst, target):
    low = 0
    high = len(lst)-1
    while high >= low:
        mid = (high + low)//2
        if target < lst[mid]:
           high = mid - 1
        elif target > lst[mid]:
            low = mid + 1
        else:
            return mid

    return (-1 * (mid+1))

问题是这样,我想在实际运行它给出的函数时将列表target_values添加到第一个正确的顺序

lst_test = [3, 4, 6, 7]
target_values = [1, 3, 5, 8]

for t in target_values:
    i = binarySearch(lst_test, t)
    if (i < 0):
        print("In", lst_test, t, "is going to be inserted at index",-1*(i+1))
        lst_test.insert((i+1)*-1, t)
    else:
        print("In", lst_test, t, "was found at index", i)
print("The final list is:", lst_test)

这很奇怪,它的工作却只在通话的最后部分失败了 有什么方法可以解决这个问题吗?最终名单应为[1,3,4,5,6,7,8]

根据要求,我跟踪了我的二进制搜索算法,它的质量很差。我希望这会有所帮助

In [3, 4, 6, 7] 1 is going to be inserted at index 0
In [1, 3, 4, 6, 7] 3 was found at index 1
In [1, 3, 4, 6, 7] 5 is going to be inserted at index 3
In [1, 3, 4, 5, 6, 7] 8 is going to be inserted at index 5
The final list is: [1, 3, 4, 5, 6, 8, 7]

2 个答案:

答案 0 :(得分:3)

只需更改函数即可返回<div id="LoggedAs"><span><?php echo $user_ip;?></span></div>

(-1 * (low+1))

输出:

def binarySearch(lst, target):
    low = 0
    high = len(lst)-1
    while high >= low:
        mid = (high + low)//2
        if target < lst[mid]:
           high = mid - 1
        elif target > lst[mid]:
           low = mid + 1
        else:
           return mid

    return (-1 * (low+1))

原始实现的问题是代码假定('In', [3, 4, 6, 7], 1, 'is going to be inserted at index', 0) ('In', [1, 3, 4, 6, 7], 3, 'was found at index', 1) ('In', [1, 3, 4, 6, 7], 5, 'is going to be inserted at index', 3) ('In', [1, 3, 4, 5, 6, 7], 8, 'is going to be inserted at index', 6) ('The final list is:', [1, 3, 4, 5, 6, 7, 8]) 是插入索引,但它永远不会超出循环中的当前列表,因为它应该在将值插入列表末尾时使用。

答案 1 :(得分:0)

我想我明白了。加入我推荐的印刷语句。跟踪现有列表末尾的插入。我相信你会发现你无法驱动高到足以引发列表末尾的插入;你能得到的最多就是在最后一个元素之前插入,这正是你的测试中发生的事情。