Question: I'm trying to implement a heapsort using vectors, I've filled in most of the code but it still only sorts the first number of the
I'm trying to implement a heapsort using vectors, I've filled in most of the code but it still only sorts the first number of the vector array. I dont know what i'm doing wrong. Please correct the code so that it can heapsort all the input.
CODE:
#include "maxheap.hpp"
#include
#include
#include
MaxHeap::MaxHeap() {}
MaxHeap::~MaxHeap() {}
/*
ALL YOUR CODE GOES HERE
The methods below either
- don't do anything at all, or
- return 0 just so that the code compiles
You have to implement every method in this class
*/
int MaxHeap::size() {
return arr.size();
return 0;
}
int MaxHeap::left(int parent) {
return (2*parent + 1);
return 0;
}
int MaxHeap::right(int parent) {
return (2*parent + 2);
return 0;
}
int MaxHeap::parent(int child) {
return (child - 1 )/ 2;
return 0;
}
void MaxHeap::insert(int element) {
arr.push_back(element); // add new element to the end of vector
int index = size() - 1;
percolateUp(index);
}
int MaxHeap::deleteMax() {
int temp = arr[0];
arr[0] = arr.back();
arr.pop_back();
percolateDown(0);
return temp;
}
void MaxHeap::display() {
vector
cout << "MaxHeap:- ";
for(it=arr.begin(); it!=arr.end(); ++it) {
cout << *it << " ";
}
cout << endl;
}
void MaxHeap::percolateUp(int index) {
if (index && arr[parent(index)] < arr[index])
{
swap(arr[index], arr[parent(index)]);
percolateUp(parent(index));
}
}
void MaxHeap::percolateDown(int index) {
int left_ind = left(index);
int right_ind = right(index);
int largest = index;
if (left_ind < size() && arr[left_ind] > arr[index])
{
largest = left_ind;
}
if (right_ind < size() && arr[right_ind] > arr[largest])
{
largest = right_ind;
}
if (largest != index)
{
swap(arr[index], arr[largest]);
percolateDown(largest);
}
}
void MaxHeap::heapify(vector
int left_ind = left(i);
int right_ind = right(i);
int largest = i;
if (left_ind < n && A[left_ind] > A[largest])
largest = left_ind;
if (right_ind < n && A[right_ind] > A[largest])
largest = right_ind;
if (largest != i)
{
int temp;
temp = A[i];
A[i] = A[largest];
A[largest] = temp;
heapify(A, n, largest);
}
}
void MaxHeap::heapsort(vector
vector
int i;
for(it = A.begin(); it!= A.end(); it++) //builds max heap
{
arr.push_back(*it);
}
for(i = n - 1; i > 0; i--)
{
display();
int temp;
temp = A[i];
A[i] = A[0];
A[0] = temp;
heapify(A, 0, i);
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
