【问题标题】:Priority Queue using just array and binary search仅使用数组和二进制搜索的优先级队列
【发布时间】:2015-02-26 15:02:58
【问题描述】:

所以我遇到了优先队列数据结构,实现通常是用堆或二叉树。

为什么优先级队列不能只使用简单的数组并使用二进制搜索进行插入,它仍然是 O(logn),检索时间为 O(1)。

while true {
    // We will eventually reach the search with only two or less elements remaining.
    // The insert can be in front of (first element index), between (second element index)
    // or behind of the two element (second element index + 1).
    //
    // The lowerBound is the first element index if the first element (aka middle) has a 
    // higher priority than the insert priority (last call is upperBound = middle - 1 so 
    // lowerBound unchange)
    //
    // The lowerBound will be the second element index if the first element (aka middle) 
    // has a lower priority than the insert priority (last call is lowerBound = middle + 1)
    //
    if lowerBound >= upperBound {
        // We still need to check if lowerBound is now in the second element, in which it can also 
        // be greater than priority of the second element. If so, we need to add 1 to the index 
        // (lowerBound)
        return array[lowerBound].priority > insert.priority ? lowerBound : lowerBound + 1
    }

    var middle = (lowerBound + upperBound) / 2
    let middleValue = array[middle]

    if middleValue.priority > insert.priority {
        upperBound = middle - 1
    } else { // treat equal as less than so it put the same priority in order of insertion
        lowerBound = middle + 1
    }
}

【问题讨论】:

    标签: data-structures queue priority-queue binary-search


    【解决方案1】:

    你的循环,二分搜索,只找到索引,新项目应该被插入以保持排序顺序。实际上将它插入那里是困难的部分。简而言之,这需要线性时间,我们对此无能为力。排序后的数组检索速度非常快,但插入速度很慢。二进制堆的插入和检索速度都很快(对数)。

    【讨论】:

    • 我明白了。感谢您的澄清。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2017-10-18
    • 2017-02-08
    • 1970-01-01
    • 2021-08-14
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多