Skip to main content
gamedev.net
🔒 Locked

Sorted array always heap?

Started by swiftcoder Oct 11, 2006 at 11:49 AM 2 replies 6k views
Original Post
swiftcoder
swiftcoder
So my CS professor was explaining the heap data structure to us yesterday, in mind numbing detail :) Anyway, he was explaining heap-sort, and I made the mistake of pointing out that the result of the heap-sort operation was also a valid heap. Then I went on to ask whether a sorted array is always a valid heap, and he didn't provide an answer (he said it would take too long to discuss). So perhaps one of you can answer it instead: Is there any case in which an array of integers, sorted in increasing order, is not a valid min-heap?
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]
Zahlman
Zahlman
No; it will always be valid.

Proof:

Sortedness: j <= k implies a[j] <= a[k].

Heap requirement: for all j where a[2*j] and a[2*j+1] are valid,
a[j] <= a[2*j] and a[j] <= a[2*j+1].

Since j >= 0 when those are valid, 2*j > j and 2*j + 1 > j. Therefore, sortedness implies the satisfaction of the heap criteria.

Edit: spelled out 'implies' to avoid visual confusion.
swiftcoder
swiftcoder
Thank you, that is what I thought, but it is good to see a proof.
Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]
Zahlman
Zahlman
No problem. It really isn't difficult; you should get into the habit of doing proofs for yourself (I hope the example helps you think about how to do them).

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.