Objectives of this lecture
What is a heap?
r
/ \
p m
/ \ /
o k c
|
r |
p |
m |
o |
k |
c |
|
0 |
1 |
2 |
3 |
4 |
5 |
6 |
|
Forming
a Heap.
For each value in the array 1..n, do
a. place the value into its corresponding position on the tree
b. bubble the value up the tree as high as it can go.
Steps |
Array representation |
Tree representaion |
step 1: Place h at position 1, the root |
h | i s t o r y |
h |
Step 2: i goes to position 2, but since it is larger that h we need to swap |
i h | s t o r y |
i / h |
Step3: s goes to position 3, but need to swap with h since s is larger |
s h i | t o r y |
s / \ h i |
Step4: t goes to position 4, but need to swap first with h and then with s |
t s i h o | r y |
t / \ s i / h |
Step5: o remains at 5. |
t s i h o | r y |
t / \ s i / \ h o |
Step6: r goes to position 6, but need to swap with i. |
t s r h o i | y |
t / \ s r / \ / h o i |
Step7: y goes to position 7, but it need to swap first with r and then with t |
y s t h o i r |
y / \ s t / \ / \ h o i r |
void Heapify(int list[], int listsize) {
int k, leafpos, done;
for(k=1; k<listsize; k++) {
done=0;
leafpos=k;
while((leafpos>1) && (!done))
if (list[leafpos] > list[leafpos/2]) {
Swap(leafpos, leafpos/2, list);
leafpos=leafpos/2;
} else done=1;
}
}
Heap
Sort
Repeat n-1 times
1. Exchange the root value with the last value in the tree
2. Drop the last value from the tree
3. heapify the tree
o Start at the current root node of the tree
o if the root is larger than its children, stop
o if not, exchange the root with the largest child
o consider this child to be the current root and repeat from (3)
r
/ \
p m
/ \ /
o k c
|
r |
p |
m |
o |
k |
c |
|
0 |
1 |
2 |
3 |
4 |
5 |
6 |
|
Exchange the root, r,with the last node on the tree, c. |
c p m o k r |
c / \ p m / \ / o k r |
Discard r from the tree |
c p m o k | r |
c / \ p m / \ o k |
Reheapify the tree |
p o m c k | r |
p / \ o m / \ c k |
Exchange the root, p, with the last node, k |
k o m c p | r |
k / \ o m / \ c p |
Discard p |
k o m c | p r |
k / \ o m / c |
Reheapify the tree |
k o m c | p r |
k / \ o m / c |
---and so on -- |
---and so on -- |
---and so on -- |
void HeapSort (int list[], int listsize) {
int k,
current, child, done, temp;
Heapify(list, listsize);
for
(k=listsize-1; k>=1; k--) {
Swap(k,1,list);
current=1;
child=2;
done=0;
//re-heapify
while((child<k) && (!done)) {
//if
the right child is larger, it should be the child
if((child+1<k)
&& (list[child+1]>list[child]))
child=child+1;
//if
parent is larger than its child
if
(list[current]>=list[child])
done=1;
else {
Swap(current, child, list);
current=child;
child=current*2;
}
}
}
}
Analysis: