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:
-
Given an unsorted array of integers and an integer k, your task is to find:
- The Kth smallest element.
- The Kth largest element.
- Assume that k is valid and 1 ≤ k ≤ n.
Input Format:
- n: An integer representing the number of elements in the array.
- n space-separated integers representing the elements of the array.
- k: An integer representing the position of the smallest and largest elements to be found.
Output Format:
- Print the Kth smallest and Kth largest element in the array.
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:
- 1 ≤ n ≤ 1000
- -10⁵ ≤ array[i] ≤ 10⁵
- 1 ≤ k ≤ n
Hint:
Follow these steps to solve the problem:
-
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.
-
Sort the Array:
- Use a sorting algorithm like bubble sort.
- After sorting, the array will be in ascending order.
-
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.
-
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.