Page 1 of 1

IN C++, Using Notepad ++, Compiled in Developer Command Prompt for VS 2019. Convert all the functions written in the lec

Posted: Thu Jul 14, 2022 2:27 pm
by answerhappygod
IN C++, Using Notepad ++, Compiled in Developer CommandPrompt for VS 2019.
Convert all the functions written in the lecture video in such away that they produce a min heap insteadof a max heap.
Code for heap.h
#ifndef HEAP_H#define HEAP_H
void insertHeap(int heap[], int key, int &lastIndex);void reheapUp(int heap[], int locIndex);void deleteHeap(int heap[], int &lastIndex);void reheapDown(int heap[], int locIndex, int lastIndex);void heapify(int heap[], int &lastIndex, int size);void printHeap(int heap[], int lastIndex);
#endif
Code for heap.cpp
#include "heap.h"#include <iostream>using namespace std;
void insertHeap(int heap[], int key, int &lastIndex){ lastIndex++; heap[lastIndex] = key; reheapUp(heap, lastIndex);}
void reheapUp(int heap[], int locIndex){ if(locIndex == 0) //Indicates we're at the root.Exit recursion { return; } int parentIndex = (locIndex - 1)/2; if(heap[parentIndex] < heap[locIndex]) { int hold =heap[parentIndex]; heap[parentIndex] =heap[locIndex]; heap[locIndex = hold]; reheapUp(heap,parentIndex); }}
void deleteHeap(int heap[], int &lastIndex){ if(lastIndex < 0) { cout << "Heap isempty."; return; } heap[0] = heap[lastIndex]; lastIndex--; reheapDown(heap, 0, lastIndex);}
void reheapDown(int heap[], int locIndex, int lastIndex){ int leftIndex, rightIndex, biggestIndex,leftValue, rightValue; leftIndex = 2*locIndex + 1; if(leftIndex <= lastIndex) //Means left childexists { leftValue =heap[leftIndex]; rightIndex = leftIndex +1; if(rightIndex <=lastIndex) { rightValue= heap[rightIndex]; } else { //Haveleft child, but no right child. rightValue= leftValue - 1; //Always less than leftValue } if(leftValue >rightValue) { biggestIndex = leftIndex; } else { biggestIndex = rightIndex; } // Check if we shouldswap if(heap[biggestIndex] >heap[locIndex]) { int hold =heap[locIndex]; heap[locIndex] = heap[biggestIndex]; heap[biggestIndex] = hold; reheapDown(heap, biggestIndex, lastIndex); } }}
Code for mainheap.cpp
#include "heap.h"#include <iostream>#include <cstdlib> // for rand and srandusing namespace std;
int main(){ int heap[10]; int size = 10; int min = 0, max = 100; int newValue; int lastIndex = -1; for(int i = 0; i < size; i++) { newValue = rand()%(max+1 -min) + min; cout << newValue<< " "; insertHeap(heap, newValue,lastIndex); cout << "\nCurrently inthe array: "; for(int j = 0; j <=lastIndex; j++) cout << heap[j] << " "; cout << endl <<endl; } cout << endl << endl; for(int i = 0; i < size; i++) { cout << heap[0]<< " "; deleteHeap(heap,lastIndex); cout << "\nCurrently inthe array: "; for(int j = 0; j <=lastIndex; j++) cout << heap[j] << " "; cout << endl<<endl; } return 0; }