// PQMain.cc a main() for testing heap building routines. saunders. 9/96. typedef int itemType; // itemType must be a type on which the comparator > can be used. /////////////////////////////////////////////////////////////////////// // How to use this file to complete your homework for problem 11.9 //// //////// /////////// // 1. Complete the definition of the version of buildheap using upheap. // 2. Do these 3 compiles: // CC heapMain.cc -DNOT -o not.exe // CC heapMain.cc -DUPHEAP -o upheap.exe // CC heapMain.cc -DDOWNHEAP -o downheap.exe // 3. Do these 3 runs: // time not.exe 1000000 // time upheap.exe 1000000 // time downheap.exe 1000000 // 3a you might find it useful to to timings for other sizes of heap, to // help draw conclusions about the rate of growth of the times as // a function of the size of the heap. // 4. submit // your code for buildheap using upheap // a discussion of your conclusions from the timing runs you did. /////////////////////////////////////////////////////////////////////// //char id[10]; name of the method ("downheap", "upheap", or "not"). void buildheap(itemType a[], int size); // the method itself. #include #include "random.cc" //#include int atoi(char* s) { for (int n = 0; '0' <= *s && *s <= '9'; s++) n = 10*n + (*s - '0'); return *s == 0 ? n : -1; } #ifdef UPHEAP char* id = "upheap"; void upheap(itemType a[], int N, int k); void buildheap(itemType a[], int size) { // define a version of buildheap which uses upheap here } void upheap(itemType a[], int N, int k){ // define upheap here // } #endif #ifdef DOWNHEAP char* id = "downheap"; void downheap(itemType a[], int N, int k); void buildheap(itemType a[], int size) { for (int i = size/2; i >= 1; i--) // invariant: a[i+1 .. N] has the heap property. downheap(a, size, i); } void downheap(itemType a[], int N, int k){ // Assumes a[k+1 .. N] has the heap property. // Permutes elements of a so that a[k .. N] has the heap property. int j; itemType v = a[k]; // a[N/2 + 1 .. N] automatically has the heap property. // It's just a bunch of leaves. while (k <= N/2) { j = k+k; if (j < N && a[j] < a[j+1]) j++; if (a[j] <= v) break; a[k] = a[j]; k = j; } a[k] = v; } #endif #ifdef NOT char* id = "not"; void buildheap(itemType a[], int size) {} #endif int main(int argc, char* argv[]){ //test it if (argc != 2) { cout << " usage: time " << argv[0] << " n\n"; cout << "where n is the number of elements to be in the heap.\n"; return 0; } int N = atoi(argv[1]); itemType* a = new itemType[N+1]; // setup the random values in the array for(int i = 1; i <= N; i++) a[i] = random()%(10*N); // do it buildheap(a, N); // output for identification cout << id << " " << N; // check correctness int success = 1; for(i = 1; i <= N/2; i++) if (a[i] < a[2*i] || (2*i + 1 <= N && a[i] < a[2*i + 1])) success = 0; cout << (success ? ", Good heap \n" : ", Not a heap\n" ); return 0; }