소스 검색

fixed the mysterious removeMax and removeKey zeros. Priority Queue seems to be working now

Natalie Pueyo 8 년 전
부모
커밋
b846e12f89
2개의 변경된 파일13개의 추가작업 그리고 14개의 파일을 삭제
  1. 11 11
      program2/priorityqueue.cpp
  2. 2 3
      program2/testCode.cxx

+ 11 - 11
program2/priorityqueue.cpp

@@ -37,9 +37,10 @@ void PriorityQueue::insert(int key){
     std::cout << "PriorityQueue::insert called on full priority queue" << std::endl;
     return;
   }
+  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 + 1;
+  int keyIndex = heap_size;
   // heapify up until the heap properties are restored
   heapifyUp(key, keyIndex);
 }
@@ -55,19 +56,20 @@ void PriorityQueue::removeMax(){
     heap_size--;
   } else {
     // remove the max value (at root)
-    heapArray[1] = heapArray[heap_size + 1];
+    heapArray[1] = heapArray[heap_size];
     heapifyDown(1);
-    heap_size--; // causing that zero to appear?
   }
 }
 
 void PriorityQueue::removeKey(int key){
   for (int i = 1; i <= heap_size; i++) {
     if (heapArray[i] == key) {
-      // change the key at correct index into something larger than maxValue
-      heapArray[i] = heapArray[1] + 10;
-      heapifyUp(heapArray[i], i);
-      removeMax();
+      // change the key at index with last heap key
+      change(&heapArray[i], &heapArray[heap_size]);
+      // erase the last node erasing the unwanted key
+      heap_size--;
+      // heapify to preserve heap properties
+      heapifyDown(i);
       return;
     }
   }
@@ -105,17 +107,15 @@ void PriorityQueue::heapifyDown(int index){
 
   if (largerKeyIndex != index) {
     change(&heapArray[index], &heapArray[largerKeyIndex]);
-    // apparently heapArray[largerKeyIndex] doesn't have a value?!?! fix this later
-    std::cout << "when does zero appear? " << heapArray[largerKeyIndex] << std::endl;
     heapifyDown(largerKeyIndex);
-    //heap_size--;
+    heap_size--;
   }
 }
 
 void PriorityQueue::heapifyUp(int key, int index){
   int curIndex = index;
   int parentIndex = (curIndex)/2;
-  heap_size++;
+  //heap_size++;
   // insert new key into the end of the array
   heapArray[curIndex] = key;
 

+ 2 - 3
program2/testCode.cxx

@@ -13,12 +13,11 @@ int main(){
   h.insert(2);
   h.insert(15);
   h.insert(5);
-  //h.removeKey(2);
+  h.removeKey(2);
   h.insert(4);
   h.insert(45);
-  //h.removeKey(15);
+  h.removeKey(15);
   h.removeMax();
-  //h.decreaseKey(2, 1);
   h.printArray();
   return 0;
 }