Question: Please fix constructHeap() function in my code // Title: heap.cpp #include #include #include using namespace std; bool checkForHeap(vector nums) { for (int i = 0;

Please fix constructHeap() function in my code

// Title: heap.cpp #include #include #include using namespace std;

bool checkForHeap(vector nums) { for (int i = 0; i <= (nums.size()-2)/2; i++) { if (nums[2*i + 1] > nums[i]) { return false; } if (nums[2*i + 2] > nums[i]) { return false; } } return true; }

void constructHeap(vector nums) { int k, v, j; bool heap; for (int i = floor(nums.size()/2); i >= 1; i--) { k = i; v = nums[k]; heap = false; while (!heap && (2*k <= nums.size())) { j = 2*k; if (j < nums.size()) { if (nums[j] < nums[j+1]) { j = j + 1; } } if (v >= nums[j]) { heap = true; } else { nums[k] = nums[j]; k = j; } } nums[k] = v; }

for (int num : nums) { cout << num << " "; } }

int main() { int user_size, user_choice; vector nums; cout << "Input size: "; cin >> user_size; cout << "Enter numbers: ";

for (int i = 0; i < user_size; i++) { int num; cin >> num; nums.push_back(num); }

if (!checkForHeap(nums)) { cout << "This is NOT a heap." << endl; cout << "Heap constructed: "; constructHeap(nums); cout << endl; cout << "Select an operation" << endl; cout << " 1. Insert a number" << endl; cout << " 2. Delete the max" << endl; cout << " 3. Heapsort & Quit" << endl; cin >> user_choice; while (user_choice == 1 || user_choice == 2 || user_choice == 3) { if (user_choice == 1) { cout << "Enter a number: "; int insert_num; cin >> insert_num; nums.push_back(insert_num); for (int i = 0; i < nums.size(); i++) { cout << nums[i] << " "; } cout << endl; cout << "Updated heap: "; constructHeap(nums); } /*else if (user_choice == 2) {

} else if (user_choice == 3) {

}*/ cout << "Select an operation" << endl; cout << " 1. Insert a number" << endl; cout << " 2. Delete the max" << endl; cout << " 3. Heapsort & Quit" << endl; cin >> user_choice; } } else { cout << "This is a heap." << endl; cout << "Select an operation" << endl; cout << " 1. Insert a number" << endl; cout << " 2. Delete the max" << endl; cout << " 3. Heapsort & Quit" << endl; // cin >> user_choice; // while (user_choice == 1 || user_choice == 2 || user_choice == 3) { // if (user_choice == 1) {

// } else if (user_choice == 2) {

// } else if (user_choice == 3) {

// } // cout << "Select an operation" << endl; // cout << " 1. Insert a number" << endl; // cout << " 2. Delete the max" << endl; // cout << " 3. Heapsort & Quit" << endl; // cin >> user_choice; // } }

system("pause"); return 0; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!