Print Kth Smallest and Kth Largest Element of an Array
“Print Kth Smallest and Kth Largest Element of an Array” is again a basic problem of array data structure. Here, we are given an unsorted array of size ‘n’ and our task is to print kth smallest and kth largest element of an array, where k<=n.
Example (Print Kth Smallest and Kth Largest Element of an Array):
INPUT: Arr[5] = {55, 33, 11, 22, 44} K = 2 OUTPUT: Kth smallest = 22 Kth largest = 44
The steps required to print kth smallest and kth largest element of an array are as follows:
- Scan array size.
- Scan array elements.
- Sort the array.
- Print kth element as kth smallest element.
- Print (n-k)th element as kth largest element.
C++ Program to print kth smallest and kth largest element of an array is as follows:
/* Program to print kth smallest and kth largest element of an array */
#include<bits/stdc++.h>
using namespace std;
int main()
{
/* Scan array size */
int n;
cout<<"Enter array size: ";
cin>>n;
/* Scan array elements */
int arr[n];
cout<<"\nEnter array elements:";
for(int i = 0; i < n; i++)
cin>>arr[i];
/* Scan kth number */
int k;
cout<<"\nEnter kth element:";
cin>>k;
/* Sort the array using in-built function */
sort(arr,arr+n);
/* Printing the result */
cout<<"\nKth smallest element is "<<arr[k-1];
cout<<"\nKth largest element is "<<arr[n-k];
}
OUTPUT: Enter array size: 5 Enter array elements: 22 55 11 44 33 Enter kth element: Kth smallest element is 22 Kth largest element is 44 Time Complexity: O(nlogn), for sorting the array
Related Posts:
- Program to find absolute difference between sum of odd index elements and even index elements.
- Program to find smallest and largest element of the array.
- Program to count occurrences of a particular element in an array.
- Program to search an element in an Array (Linear Search).
- Program to Rotate Array Elements by ‘D’ positions.
- Program to find most frequent element in an array.
- Program to find pair in an array with given sum.
- Program to find first repeating element of an array.
- Program to merge two sorted arrays.
- Program to find missing number in an array.
- Program to sort if array is sorted.
- Program to copy One Character Array to Another.
- Program to Concatenate Two Character Arrays.
- Program to Check whether given String is Palindrome or not.
- Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
- Program to count total number of words in a string.
- Program to Remove all the blank spaces from the String.
- Program to check if String is isogram or not.
- Program to Reverse Each word of the String.
- Program to Print All the Substring of the Given String.