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