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:

  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 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:

  1. Program to find absolute difference between sum of odd index elements and even index elements.
  2. Program to find smallest and largest element of the array.
  3. Program to count occurrences of a particular element in an array.
  4. Program to search an element in an Array (Linear Search).
  5. Program to Rotate Array Elements by ‘D’ positions.
  6. Program to find most frequent element in an array.
  7. Program to find pair in an array with given sum.
  8. Program to find first repeating element of an array.
  9. Program to merge two sorted arrays.
  10. Program to find missing number in an array.
  11. Program to sort if array is sorted.
  12. Program to copy One Character Array to Another.
  13. Program to Concatenate Two Character Arrays.
  14. Program to Check whether given String is Palindrome or not.
  15. Program to convert lower-case alphabet to upper-case alphabet and vice-versa.
  16. Program to count total number of words in a string.
  17. Program to Remove all the blank spaces from the String.
  18. Program to check if String is isogram or not.
  19. Program to Reverse Each word of the String.
  20. Program to Print All the Substring of the Given String.

You may also like...