IN C++, Using Notepad ++, Compiled in Developer CommandPrompt for VS 2019.
For this assignment fill an array of 10 integers with randomvalues ranging from 0 to 100.
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 done 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. Exitrecursion{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 is empty.";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 child exists{leftValue = heap[leftIndex];rightIndex = leftIndex + 1;if(rightIndex <= lastIndex){rightValue = heap[rightIndex];}else{//Have left child, but no right child.rightValue = leftValue - 1; //Always less than leftValue}if(leftValue > rightValue){biggestIndex = leftIndex;}else{biggestIndex = rightIndex;}// Check if we should swapif(heap[biggestIndex] > heap[locIndex]){int hold = heap[locIndex];heap[locIndex] = heap[biggestIndex];heap[biggestIndex] = hold;reheapDown(heap, biggestIndex, lastIndex);}}}
IN C++, Using Notepad ++, Compiled in Developer Command Prompt for VS 2019. For this assignment fill an array of 10 inte
-
- Site Admin
- Posts: 899603
- Joined: Mon Aug 02, 2021 8:13 am