Cranes at VIIT Q4

Find Kth Smallest and Largest Element in an Array

Write a C program that finds the Kth smallest and Kth largest element in an unsorted array.

Problem Statement:

Input Format:

Output Format:

Example Inputs & Outputs:

Enter the number of elements: 6
Enter the elements: 7 10 4 3 20 15
Enter the value of k: 3
3rd smallest element: 7
3rd largest element: 10
            
Enter the number of elements: 5
Enter the elements: 12 3 5 7 19
Enter the value of k: 2
2nd smallest element: 5
2nd largest element: 12
            

Constraints:

Hint:

Follow these steps to solve the problem:

  1. Take Input:
    • Read an integer n representing the number of elements in the array.
    • Read an array of n integers.
    • Read an integer k representing the position of the smallest and largest elements.
  2. Sort the Array:
    • Use a sorting algorithm like bubble sort.
    • After sorting, the array will be in ascending order.
  3. Find the Kth Smallest and Largest Elements:
    • The Kth smallest element is at position k-1 in the sorted array.
    • The Kth largest element is at position n-k in the sorted array.
  4. Print Results:
    • Print the Kth smallest and Kth largest elements.

Formula Breakdown:

Task: Implement the above logic and write a C program to find the Kth smallest and Kth largest elements in an array.