/* This program implements Push() on a heap. Its main reads a vector of integers on standard input, and then pushes them all onto a heap, printing the heap each time. */ #include #include #include #include using namespace std; /* Push the value val onto the heap. */ void Push(vector &heap, int val) { int i, p; i = heap.size(); heap.push_back(val); // Put the value onto the end of the heap. while (i > 0) { // Percolate up, starting at i. p = (i-1) / 2; // You stop when you reach the root, or when the parent's value if (heap[p] > val) { // is less than or equal to val. heap[i] = heap[p]; heap[p] = val; i = p; } else { return; } } } int main() { vector v; vector heap; int val; size_t i, j; /* Read values into a vector */ while (cin >> val) v.push_back(val); /* Repeatedly call Push and print the heap. */ for (i = 0; i < v.size(); i++) { Push(heap, v[i]); printf("Push %2d : ", v[i]); for (j = 0; j < heap.size(); j++) printf(" %2d", heap[j]); printf("\n"); } return 0; }