【发布时间】: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