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:

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 number of the array are as follows:

  1. Scan array size.
  2. Scan array elements.
  3. Sort the array.
  4. Print kth element as kth smallest element.
  5. Print (n-k)th element as kth largest element.

C++ Program to print kth smallest element and kth largest element is as follows:

/* Program to print kth largest element and kth smallest element */  
#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:

  1. Program to find equilibrium index of an Array.
  2. Program to find majority element of an Array.
  3. Program to find mean of the Array.
  4. Program to sort an Array of 0s and 1s.
  5. Program to Reverse an Array.
  6. Program to count number of odd numbers and even numbers in an array.
  7. Program to find absolute difference between sum of odd index elements and even index elements.
  8. Program to find smallest and largest element of the array.
  9. Program to count occurrences of a particular element in an array.
  10. Program to search an element in an Array (Linear Search).
  11. Program to Rotate Array Elements by ‘D’ positions.
  12. Program to find most frequent element in an array.
  13. Program to find pair in an array with given sum.
  14. Program to find first repeating element of an array.
  15. Program to merge two sorted arrays.
  16. Program to find missing number in an array.
  17. Program to sort if array is sorted.
  18. Program to print Alternate Elements of an Array.
  19. Program to swap kth element from beginning to kth element from end in an Array.
  20. Program to print all possible subarrays of the given array.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *