Sum Of Two Kth Smallest Elements By Heap sort 2024(Required)

Time limit: 5000ms
Memory limit: 256mb

Description:
In this exercise, you are required to use heap sort program to find Kth smallest element in an array. The elements in an array can be in any order and consist of distinct integers.
Given an array a[], K1 and K2, printing the sum of K1th smallest element and K2th smallest element in a[].


Sample Input 1:
5
10 20 30 40 50
3 4

Sample Output 1:
Input the number of integers:
Input these integers:
Input K1 and K2:
sum of K1th and K2th smallest elements:
70

Explanation: The arrays a[] is [10,20,30,40,50], K1 is 3, K2 is 4. The K1th smallest element is 30, the K2th smallest element is 40. The sum of these two elements is 30+40=70.
The result is 70.


Sample Input 2:
5
9 8 7 6 5
2 3

Sample Output 2:
Input the number of integers:
Input these integers:
Input K1 and K2:
sum of K1th and K2th smallest elements:
13

Explanation: The arrays a[] is [9,8,7,6,5], K1 is 2, K2 is 3. The K1th smallest element is 6, the K2th smallest element is 7. The sum of these two elements is 6+7=13.
The result is 13.


Code Template:

#include <stdio.h>
#include <stdlib.h>

void swap(int *a, int *b) {
    /*
        Fill in your code here...
        function to swap two elements
    */
}

void adjust(int arr[], int n, int i) {
    /*
        Fill in your code here...
        complete adjust function to maintain the min-heap property
    */
}

// build min heap function
void buildMinHeap(int arr[], int n) {
    for (int i = (n - 1) / 2; i >= 0; --i) {
        adjust(arr, n, i);
    }
}


void printSumOfTwoKSmallest(int arr[], int n, int k1, int k2) {
    buildMinHeap(arr, n);

    /*
        Fill in your code here...
        print sum of K1th smallest elements and K2th smallest elements in an array
    */
}

int main() {
    int k1, k2, n, *arr;
    printf("Input the number of integers:\n");
    scanf("%d",&n);
    arr = (int*)malloc(sizeof(int)*n);
    printf("Input these integers:\n");
    for(int i=0; i<n; i++)
        scanf("%d", &arr[i]);
    printf("Input K1 and K2:\n");
    scanf("%d",&k1);
    scanf("%d",&k2);
	
    printf("sum of K1th and K2th smallest elements:\n");
    printSumOfTwoKSmallest(arr, n, k1, k2);

    return 0;
}

Submit