Browse Source

fixed priorityqueue removeMax so that it and not the heapify method changes the array size. Fixed the mysterious disappearing numbers bug

Natalie Pueyo 8 năm trước cách đây
mục cha
commit
c415ae9a77
2 tập tin đã thay đổi với 10 bổ sung13 xóa
  1. 7 9
      program2/heapsort.cxx
  2. 3 4
      program2/priorityqueue.cpp

+ 7 - 9
program2/heapsort.cxx

@@ -33,31 +33,29 @@ int main(int argc, char** argv) {
 
     if (sampleName != "metadata") {
       nlohmann::json topOfHeap;
+
       for (auto arrayItr = jsonObject[sampleName].begin(); arrayItr != jsonObject[sampleName].end(); ++arrayItr) {
         // insert each array element into heap
         currValue = *arrayItr;
         sampleHeap.insert(currValue);
       }
-      std::cout << "before sorting" << std::endl;
-      sampleHeap.printArray();
+
+      // insert heap top key values into an array backwards to sort from min to max
       for (int i = n - 1; i >= 0; i--) {
-        // insert heap.top into array A backwards to sort the array from min to max
         A[i] = sampleHeap.returnMax();
-        // remove the max value from the heap
         sampleHeap.removeMax();
-        std::cout << "after sorting" << std::endl;
-        sampleHeap.printArray();
       }
+
+      // convert the new array into a JSON object
       for (int j = 0; j <= n - 1; j++) {
         // adding values directly to JSON object
         topOfHeap.push_back(A[j]);
-        std::cout << A[j] << ", ";
       }
-      std::cout << std::endl;
       outputJSON[sampleName] = topOfHeap;
     }
   }
-
+  outputJSON["metadata"]["arraySize"] = n;
+  outputJSON["metadata"]["numSamples"] = jsonObject["metadata"]["numSamples"];
   std::cout << outputJSON << std::endl;
 
   // clean up memory

+ 3 - 4
program2/priorityqueue.cpp

@@ -17,9 +17,8 @@ void PriorityQueue::insert(int key){
     std::cout << "PriorityQueue::insert called on full priority queue" << std::endl;
     return;
   }
+  // increase array size and insert new key at end
   heap_size++;
-  // heap starts at index 1 so when I want to insert a new node, it should be at the
-  // nex index?
   int keyIndex = heap_size;
   // heapify up until the heap properties are restored
   heapifyUp(key, keyIndex);
@@ -38,7 +37,7 @@ void PriorityQueue::removeMax(){
   }
 
   if (heap_size == 1){
-    heapArray[0] == 0;
+    //heapArray[0] == 0;
     heap_size--;
   } else if (heap_size == 2) { // need to check if at root to avoid error
     heapArray[1] = heapArray[2];
@@ -47,6 +46,7 @@ void PriorityQueue::removeMax(){
     // remove the max value (at root)
     heapArray[1] = heapArray[heap_size];
     heapifyDown(1);
+    heap_size--;
   }
 }
 
@@ -102,7 +102,6 @@ void PriorityQueue::heapifyDown(int index){
   if (largerKeyIndex != index) {
     change(&heapArray[index], &heapArray[largerKeyIndex]);
     heapifyDown(largerKeyIndex);
-    heap_size--;
   }
 }