Question: 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

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 Programming Questions!