// this code is used from project 6 MinHeap extractMin(MinHeap *heap){ if(heapsize == 0) return NULL; int index=0; MinHeap n = malloc(sizeof(MinHeap)); int a; n = heap[0]; heapsize--; for (a=1; a<=heapsize ;a++) { if(heap[a]->value < n->value){ n = heap[a]; // find the small node index = a; } } heap[0] = heap[heapsize]; // change node with its new position position[heap[0]->id]=heapsize; position[heap[heapsize]->id]=0; Min_Heapify(heap, 0); // call min heapify function with parent node (0) return n; }
void Min_Heapify(LinkedList *s, int i) { int leftChild = 2 * i, rightChild = 2 * i + 1, min = -1; if (leftChild <= s->GetLength&&s->GetPointData(leftChild) < s->GetPointData(i)) min = leftChild; else { min = i; } if (rightChild <= s->GetLength&&s->GetPointData(rightChild) < s->GetPointData(min)) { min = rightChild; } if (min != i) { //交换s->GetPointData(i)和s->GetPointData(min) Min_Heapify(s,min); } }
// this code is used from project 3 void Min_Heapify(MinHeap *heap, int id){ // sort sub trees to decide parent by exchanging leaf and root int l = Left(id); int r = Right(id); int smallest; if(l <= heapsize && heap[l]->value < heap[id]->value){ smallest = l; }else{ smallest = id; } if(r <= heapsize && heap[r]->value < heap[smallest]->value){ smallest = r; } if(smallest != id){ // decide smallest one and exchange with leaf position[heap[smallest]->id] = id; position[heap[id]->id] = smallest; MinHeap temp = heap[id]; heap[id] = heap[smallest]; heap[smallest] = temp; Min_Heapify(heap, smallest); } }