Loyola College in Maryland
CS 462 - Algorithm Analysis
Spring 2004
Loyola College >
Department of Computer Science >
Dr. James Glenn >
CS 462 >
Examples >
Project 1 Heap Example
| Heap |
| Priority | 0 | 1 | 6 | 10 | 80 |
| Index in Data | 3 | 2 | 0 | 1 | 3 |
| Data |
| Key | Index in Heap |
| DC | 2 |
| Philly | 3 |
| Dallas | 1 |
| Seattle | 4 |
|
| Map |
| Key | Index in Data |
| DC | 0 |
| Philly | 1 |
| Dallas | 2 |
| Seattle | 3 |
|
To complete the removal of Kansas City, we must fix the heap:
- swap heap[0] where KC is with heap[4];
- the index in heap[0] is now 3, so change index in data[3] to 0;
- shrink the heap;
- swap heap[0] and heap[1];
- the indices in the heap elements we just swapped are 3 and 2, so
swap the indices in data[3] and data[2];
- swap heap[1] and heap[3];
- the indicies in the heap elements we just swapped are 1 and 3, so
swap the indices in data[1] and data[3].
The result should be the following
| Heap |
| Priority | 1 | 10 | 6 | 80 |
| Index in Data | 2 | 1 | 0 | 3 |
| Data |
| Key | Index in Heap |
| DC | 2 |
| Philly | 1 |
| Dallas | 0 |
| Seattle | 3 |
|
| Map |
| Key | Index in Data |
| DC | 0 |
| Philly | 1 |
| Dallas | 2 |
| Seattle | 3 |
|
To add New York with priority 3 we
- add an item at index 4 in the heap and the data table;
- add an item to the map;
- swap heap[4] and heap[1];
- the indices in the heap elements we just swapped are 4 and 1, so
swap the indices in data[4] and data[1].
The result should be the following
| Heap |
| Priority | 1 | 3 | 6 | 80 | 10 |
| Index in Data | 2 | 4 | 0 | 3 | 1 |
| Data |
| Key | Index in Heap |
| DC | 2 |
| Philly | 4 |
| Dallas | 0 |
| Seattle | 3 |
| NY | 1 |
|
| Map |
| Key | Index in Data |
| DC | 0 |
| Philly | 1 |
| Dallas | 2 |
| Seattle | 3 |
| NY | 4 |
|
To remove the item with the lowest priority, we
- Follow Craig and Lara's suggestion to swap heap[0] and
heap[4] first.
- the indices in the heap elements we just swapped are 1 and 2, so
swap the indices in data[1] and data[2];
- the item we want is now at the end of the heap, so remember the
information there (priority 1, index 2) and shrink the heap;
- remember the key from data[2] (Dallas), copy
data[4] over data[2], shrink data,
and remove Dallas from the map;
- the pointers from data and the map to the new
data[2] (now NY, 1) are incorrect, so fix them by
setting the index in heap[1] to 2 and mapping
NY to 2;
- fix the heap ordering by swapping heap[0] with
heap[1];
- the indices in the heap elements we just swapped are 1 and 2, so
swap the indices in data[1] and data[2].
The result should be the following
| Heap |
| Priority | 3 | 10 | 6 | 80 |
| Index in Data | 2 | 1 | 0 | 3 |
| Data |
| Key | Index in Heap |
| DC | 2 |
| Philly | 1 |
| NY | 0 |
| Seattle | 3 |
|
| Map |
| Key | Index in Data |
| DC | 0 |
| Philly | 1 |
| Seattle | 3 |
| NY | 2 |
|