0

I am finding conflicting information on the search on a binary heap. According to this, https://en.wikipedia.org/wiki/Binary_heap, it's O(n) (edit: it's actually O(log n)), according to this, Search an element in a heap, it's O(n/2).

Community
  • 1
  • 1
  • I am sorry, I meant that the wikipedia link says it's O(log n). – tobias_theblowhard May 23 '16 at 15:48
  • A true binary heap would be O(n/2) because of the *heap property* mentioned on Wikipedia: *If A is a parent node of B then the key of node A is ordered with respect to the key of node B with the same ordering applying across the heap.* The ordering essentially splits the effort of the search in half. However, that complexity is linear on a graph so it essentially averages out to O(n). The binary search tree has ordered children and makes it possible to do a true binary search which has a complexity of O(log n). – Alex W May 23 '16 at 16:37
  • If "Search" means searching the heap for a particular datum, then it should be `O(n)`. I'm not sure what the wiki page actually means. But usually heaps do not support the "search" operation - they are just not designed to do that. Maybe someone should modify the wiki page, or state it more clearly. – WhatsUp May 23 '16 at 16:39
  • 2
    That Wikipedia article looks wrong. You can't search a binary heap in time O(log n), and heaps aren't designed to be searched that way. – templatetypedef May 23 '16 at 16:41

1 Answers1

0

Wikipedia was just wrong about that. Binary heaps are not designed to be searched for individual elements, and are optimized just to give access to the smallest element. This is what enables them, for example, to be constructed in time Θ(n); the ordering they require isn't nearly as strict as a binary search tree.

It looks like someone has updated Wikipedia, which is good. Thanks for pointing that out!

One note - the terminology O(n / 2), while technically correct, is considered a poor use of big-O notation. Big-O notation ignores constant factors, so O(n / 2) is the same as O(n). If you want to count the specific number of operations you'll end up doing, then avoid big-O notation and say something like "exactly n / 2 comparisons are required."

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065