0

I need a solution verification. I could not find the tag so if anyone could assist me on that. Question is below.

Let A [1..n] be a max-heap with n elements. Assuming there are no duplicate keys.

Write pseudocode for finding the smallest element in A. Then find the RT using O-notation

My attempt:

minIndex=1
min=A[1]
i=0
while(i <= n)
  if A[i]<min
     min=A[i]
     minIndex = i
  i+=1

Assuming that the pseudocode is correct. Does the max-heap change anything?

The running time is O(n).

GiBiT
  • 311
  • 1
  • 8
  • 20
  • 1
    You don't need both `min` and `minIndex`, you can just pick one. (because `A[minIndex] = min`). Also, one generally picks the first element as the min and start the loop from the second, not the second and start from the first. – Bernhard Barker Oct 08 '13 at 16:19
  • So `A[minIndex] = min` solves the second half of your comment? – GiBiT Oct 08 '13 at 16:24
  • 1
    Removing `min` and changing `A[i] – Bernhard Barker Oct 08 '13 at 16:36
  • Awesome, I see what your saying now. Thank you greatly. – GiBiT Oct 08 '13 at 16:39
  • 1
    Also, you can start at `i=ceiling(n/2)`, since the minimum is guaranteed to be one of the leaf nodes. This will make the running time twice as fast, but it is still O(n). – mrip Oct 08 '13 at 16:42
  • @mrip I believe only if it's perfectly balanced would that work, otherwise there may be a leaf somewhere else. – Bernhard Barker Oct 08 '13 at 16:44
  • BTW if removing the `min` I would have an issue with `min=A[i]` should I change that to `A[minIndex]=A[i]` – GiBiT Oct 08 '13 at 16:45
  • @Dukeling It doesn't have to be perfectly balanced, so long as it doesn't have any missing values, meaning that leaves are filled in from the left (which is the usual structure for an array-backed heap). The structural constraint is that `A[i]>A[2i],A[2i+1]`, so if this holds it is not necessary to check any `i – mrip Oct 08 '13 at 16:51

0 Answers0