Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

I have written an algorithm that can output k smallest elements in an array of length n using heap. The time complexity is O(n log

I have written an algorithm that can output k smallest elements in an array of length n using heap. The time complexity is O(n log k).

However, it was brought to my attention that some of the logical flows and conditions are incorrect. I have put the code down below and left 5 blanks open where I was told that I was wrong. Could you please teach me what the blanks could be filled with ? Thank you in advance ! :)

void heapify(int arr[], int num, int i)

{

int largest = i; // Initialize largest as root

int l = 2 * i + 1; // left node

int r = 2 * i + 2; // right node

// If left child is larger than root

if (l < num && arr[l] > arr[largest])

largest = l;

if (1.______________________________)

largest = r;

if (2.__________) {

swap(arr[i], arr[largest]);

// Recursively heapify the affected sub-tree

heapify(arr, num, largest);

}

}

void find_k_smallest(int arr[], int n, int k)

{

// Build heap (rearrange array)

for (int i = k / 2 - 1; i >= 0; i--)

3.__________________;

for (int i = k; i < n; i++) {

if (arr[i] < arr[0])

{

4._________________;

5._________________;

}

}

}

int main()

{

int n;

cin >> n; // size of the array

int arr[n];

for (int i = 0; i < n ; ++i) {

cin >> arr[i];

}

int k;

cin >> k; //

find_k_smallest(arr, n,k);

cout << k << '' smallest elements are'' << endl;

for (int j = 0; j < k ; ++j) {

cout << arr[j] << '' '';

}

}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Modern Dental Assisting

Authors: Doni Bird, Debbie Robinson

13th Edition

978-0323624855, 0323624855

Students also viewed these Programming questions