Question

Can Anyone help me to convert Below code to C++! Thanks For example, in C++, the...

Can Anyone help me to convert Below code to C++!

Thanks

For example, in C++, the function headers would be the following:
class MaxHeap {
vector<int> data;
public:
MaxHeap() {
// ...
}
int size() {
// ...
}
int maxLookup() {
// ...
}
void extractMax() {
// ...
}
void insert(int data) {
// ...
}
void remove(int index) {
// ...
}
};

========================

import java.util.Arrays;
import java.util.Scanner;

public class MaxHeap {
    Integer[] a;
    int size; // size of the heap
    int currentHeight = 1;

    public MaxHeap() {
        a = new Integer[(int) (Math.pow(2, currentHeight) - 1)];
    }

    private void increaseHeight() {

        Integer aNew[] = new Integer[(int) (Math.pow(2, currentHeight + 1) - 1)];

        for(int i=0; i<(int) (Math.pow(2, currentHeight) - 1); i++) {
            aNew[i] = a[i];
        }
        currentHeight++;
        a = aNew;
    }

    public int getSize() {
        return size;
    }

    private int parent(int pos) {
        return (pos - 1)/ 2;
    }

    private int leftChild(int pos) {
        return 2 * pos + 1;
    }

    private int rightChild(int pos) {
        return 2 * pos + 2;
    }

    private boolean isLeaf(int pos) {
        if (pos >= (size / 2) && pos <= size) {
            return true;
        }
        return false;
    }

    private void swap(int fpos, int spos) {
        int tmp;
        tmp = a[fpos];
        a[fpos] = a[spos];
        a[spos] = tmp;
    }

    public void heapify(int pos) {
        if (!isLeaf(pos)) {
            if ((a[leftChild(pos)] != null && a[pos] < a[leftChild(pos)] )||(a[rightChild(pos)] != null &&  a[pos] < a[rightChild(pos)])) {
                if(a[rightChild(pos)] == null) {
                    swap(pos, leftChild(pos));
                    heapify(leftChild(pos));
                } else if(a[leftChild(pos)] == null) {
                    swap(pos, rightChild(pos));
                    heapify(rightChild(pos));
                } else if (a[leftChild(pos)] > a[rightChild(pos)]) {
                    swap(pos, leftChild(pos));
                    heapify(leftChild(pos));
                } else {
                    swap(pos, rightChild(pos));
                    heapify(rightChild(pos));
                }
            }
        }
    }

    public static void main(String[] args) {
        MaxHeap heap = new MaxHeap();

        Scanner in = new Scanner(System.in);

        String line;
        int commands = in.nextInt();

        for(int i=0; i<commands; i++) {
            line = in.nextLine();
            if(line.isEmpty()) {
                i--;
                continue;               
            }

            if(line.equalsIgnoreCase("size")) {
                System.out.println(heap.getSize());
            } else if(line.toLowerCase().startsWith("insert")) {
                heap.insert(Integer.parseInt(line.split(" ")[1]));
            } else if(line.equalsIgnoreCase("maxLookup")) {
                System.out.println(heap.lookup());
            } else if(line.equalsIgnoreCase("extractmax")) {
                heap.extract_max();
            } else if(line.toLowerCase().startsWith("delete")) {
                heap.remove(Integer.parseInt(line.split(" ")[1]));
            }
        }

        in.close();
    }

    public void extract_max() {
        remove(0);      
    }

    public void remove(int index) {
        a[index] = a[--size]; 
        a[size] = null;
        heapify(index);     
    }

    public void insert(Integer element) {
        if(size == (int) (Math.pow(2, currentHeight) - 1)) {
            increaseHeight();
        }

        a[size] = element;
        int current = size;
        size++;

        while (a[current] > a[parent(current)]) {
            swap(current, parent(current));
            current = parent(current);
        }
    }

    public Integer lookup() {
        if (size > 0) {
            return a[0];
        }
        return null;
    }

}
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//C++ program

#include<iostream>
#include<math.h>
using namespace std;

class MaxHeap {
   private:
int *a;
int size; // size of the heap
int currentHeight ;
  
void increaseHeight() {

int* aNew = new int [(int)pow(2,currentHeight+1)-1];

for(int i=0; i<(int)pow(2,currentHeight)-1; i++) {
aNew[i] = a[i];
}
currentHeight++;
a = aNew;
}
int parent(int pos) {
return (pos - 1)/ 2;
}
  
int leftChild(int pos) {
return 2 * pos + 1;
}
  
int rightChild(int pos) {
return 2 * pos + 2;
}
  
bool isLeaf(int pos) {
if (pos >= (size / 2) && pos <= size) {
return true;
}
return false;
}
void swap(int fpos, int spos) {
int tmp;
tmp = a[fpos];
a[fpos] = a[spos];
a[spos] = tmp;
}

public :
   MaxHeap() {
       currentHeight=1;
       size = (int)pow(2,currentHeight)-1;
a = new int [(int)pow(2,currentHeight)-1];
}


int getSize() {
return size;
}

void heapify(int pos) {
if (!isLeaf(pos)) {
if ((leftChild(pos) < size && a[pos] < a[leftChild(pos)] )||(rightChild(pos) <size && a[pos] < a[rightChild(pos)])) {
if(rightChild(pos)>=size) {
swap(pos, leftChild(pos));
heapify(leftChild(pos));
} else if(leftChild(pos) >=size) {
swap(pos, rightChild(pos));
heapify(rightChild(pos));
} else if (a[leftChild(pos)] > a[rightChild(pos)]) {
swap(pos, leftChild(pos));
heapify(leftChild(pos));
} else {
swap(pos, rightChild(pos));
heapify(rightChild(pos));
}
}
}
}


void extract_max() {
remove(0);
}

void remove(int index) {
a[index] = a[--size];
heapify(index);   
}

void insert(int element) {
if(size == (int) (pow(2, currentHeight) - 1)) {
increaseHeight();
}

a[size] = element;
int current = size;
size++;

while (a[current] > a[parent(current)]) {
swap(current, parent(current));
current = parent(current);
}
}

int lookup() {
if (size > 0) {
return a[0];
}
  
}

};

int main() {
MaxHeap heap ;
       int num;
string line;
int commands ;
cin>>commands;

for(int i=0; i<commands; i++) {
cin>>line;
if(line=="") {
i--;
continue;   
}

if(line=="size") {
cout<<heap.getSize()<<"\n";
} else if(line=="insert") {
   cout<<"Enter number : ";
   cin>>num;
heap.insert(num);
} else if(line=="maxLookup") {
cout<<heap.lookup()<<endl;;
} else if(line=="extractmax") {
heap.extract_max();
} else if(line=="delete") {
   cout<<"Enter number : ";
   cin>>num;
heap.remove(num);
}
}

return 0;
}

Add a comment
Know the answer?
Add Answer to:
Can Anyone help me to convert Below code to C++! Thanks For example, in C++, the...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • add/ remove any methods to the program. please post new code and output Min Heap: public...

    add/ remove any methods to the program. please post new code and output Min Heap: public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) {...

  • Can anyone help me to convert below code from c# to c++? // C#: public class...

    Can anyone help me to convert below code from c# to c++? // C#: public class TernaryTree { private Node m_root = null; private void Add(string s, int pos, ref Node node) { if (node == null) { node = new Node(s[pos], false); } if (s[pos] < node.m_char) { Add(s, pos, ref node.m_left); } else if (s[pos] > node.m_char) { Add(s, pos, ref node.m_right); } else { if (pos + 1 == s.Length) { node.m_wordEnd = true; } else {...

  • java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods...

    java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods commented with: // TODO: TIP: Do not just go from memory of your assignment implementation, be sure to consider carefully the constructor and method implementation provided to you. NOTE: You do not have to provide an implementation for any methods intentionally omitted public class Heap PriorityQueue implements PriorityQueue private final static int DEFAULT SIZE 10000 private Comparable [ ] storage private int currentSize: public...

  • public static int nbLeaf(BT bt, T e): This method counts and returns the number of leaf...

    public static int nbLeaf(BT bt, T e): This method counts and returns the number of leaf nodes that contain the data e. You should use the find, isLeaf and maybe otherBT methods for counting method isLeaf public boolean isLeaf (){ if (root==null) return false; else if ((current.left==null)&&(current.right==null)) return true; else return false; } method find : public boolean find(Relative rel){ switch (rel) {    case Root: // Easy case    current = root;    return true;    case Parent:   ...

  • Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: ...

    Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: package lists; import bookdata.*; public class DoublyLinkedList { int size; //Variable que define el tamano de la lista. Node head, tail; //Nodos que definen el Head y Tail en la lista. //Constructor public DoublyLinkedList(){ this.head = null; this.tail = null; this.size = 0; } //Insert a new book in alphabetic order. public void insert(Book nb){ //Creamos uno nuevo nodo con el...

  • Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time...

    Doubly Linked List The assignment is to modify the below code in any way (like changing the method of a function). Time complexity is omitted. Any methods/functions below could be changed into something different. I was thinking of changing the method of getting size of list and maybe change from numbers to letters for nodes. import java.util.Scanner; /* Class Node */ class Node { protected int data; protected Node next, prev; /* Constructor */ public Node() { next = null;...

  • Write a method called removeDuplicates that accepts a PriorityQueue of integers as a parameter and modifies...

    Write a method called removeDuplicates that accepts a PriorityQueue of integers as a parameter and modifies the queue’s state so that any element that is equal to another element in the queue is removed. For example, if the queue stores [7, 7, 8, 8, 8, 10, 45, 45], your method should modify the queue to store [7, 8, 10, 45]. You may use one stack or queue as auxiliary storage. Please also create a Main Program to test the code....

  • Please finish all the questions,Thanks Following is Appendix assume the definition of Java class Heap given in the App...

    Please finish all the questions,Thanks Following is Appendix assume the definition of Java class Heap given in the Appendix For this question, a. (2 marks Consider the following heap 30 12 20 19 6 10 18 Given the array representation of a heap discussed in class, what is the array that corre sponds to this heap? b. (5 marks) Successively insert into the heap of part (a.) 22, 35 and 11, in that order. Use the standard heap insertion algorithm....

  • From the code below with Binary Search Tree recurrence T(n)=? use the recursion method and substitution method to solve the recurrence. Find the tightest bound g(n) for T(n) you can for which T(n)= O(...

    From the code below with Binary Search Tree recurrence T(n)=? use the recursion method and substitution method to solve the recurrence. Find the tightest bound g(n) for T(n) you can for which T(n)= O(g(n)). Explain your answer and use recursion tree method. void insert(int data) { struct node *tempNode = (struct node*) malloc(sizeof(struct node)); struct node *current; struct node *parent; tempNode->data = data; tempNode->leftChild = NULL; tempNode->rightChild = NULL; //if tree is empty if(root == NULL) { root = tempNode;...

  • I need help fixing my java code for some reason it will not let me run...

    I need help fixing my java code for some reason it will not let me run it can someone pls help me fix it. class LinearProbingHashTable1 { private int keyname; private int valuename; LinearProbingHashTable1(int keyname, int valuename) { this.keyname = keyname; this.valuename = valuename; } public int getKey() { return keyname; } public int getValue() { return valuename; } } class LinearProbingHashTable2 { private final static int SIZE = 128; LinearProbingHashTable2[] table; LinearProbingHashTable2() { table = new LinearProbingHashTable2[SIZE]; for (int...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT