Skip to content
Related Articles

Related Articles

k largest(or smallest) elements in an array

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 08 Dec, 2022
Improve Article
Save Article

Write an efficient program for printing K largest elements in an array. Elements in an array can be in any order

Examples:

Input:  [1, 23, 12, 9, 30, 2, 50], K = 3
Output: 50, 30, 23

Input:  [11, 5, 12, 9, 44, 17, 2], K = 2
Output: 44, 17

Recommended Practice

Naive Approaches: To solve the problem follow the below ideas: 

1. Using Bubble sort:

Follow the below steps to solve the problem:

  • Modify Bubble Sort to run the outer loop at most K times. 
  • Print the last K elements of the array obtained in step 1

Time Complexity: O(N * K) 
Thanks to Shailendra for suggesting this approach. 

Note: Like Bubble sort, other sorting algorithms like Selection Sort can also be modified to get the K largest elements.

2. Using temporary array:

Follow the below steps to solve the problem:

  • Store the first K elements in a temporary array temp[0..K-1]
  • Find the smallest element in temp[], and let the smallest element be min
    • For each element x in arr[K] to arr[N-1]. If x is greater than the min, remove min from temp[] and insert x
    • Then, determine the new min from temp[]
  • Print final K elements of temp[]

Time Complexity: O((N – K) * K). If we want the output sorted then O((N – K) * K + K * log(K))
Thanks to nesamani1822 for suggesting this method. 

K largest(or smallest) elements in an array using sorting:

To solve the problem follow the below idea:

We can sort the input array in descending order so that the first K elements in the array are the K largest elements

Follow the below steps to solve the problem:

  • Sort the elements in descending order
  • Print the first K numbers of the sorted array

Below is the implementation of the above approach:

C++




// C++ code for K largest elements in an array
#include <bits/stdc++.h>
using namespace std;
 
void kLargest(int arr[], int n, int k)
{
    // Sort the given array arr in reverse order.
    sort(arr, arr + n, greater<int>());
 
    // Print the first kth largest elements
    for (int i = 0; i < k; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    kLargest(arr, n, k);
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

C




// C code for k largest elements in an array
#include <stdio.h>
#include <stdlib.h>
 
// Compare function for qsort
int cmpfunc(const void* a, const void* b)
{
    return (*(int*)b - *(int*)a);
}
 
void kLargest(int arr[], int n, int k)
{
    // Sort the given array arr in reverse order.
    qsort(arr, n, sizeof(int), cmpfunc);
    // Print the first kth largest elements
    for (int i = 0; i < k; i++)
        printf("%d ", arr[i]);
}
 
// Driver code
int main()
{
    int arr[] = { 1, 23, 12, 9, 30, 2, 50 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
    kLargest(arr, n, k);
}
 
// This code is contributed by Aditya Kumar (adityakumar129)

Java




// Java code for k largest elements in an array
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
 
class GFG {
    public static void kLargest(Integer[] arr, int k)
    {
        // Sort the given array arr in reverse order
        // This method doesn't work with primitive data
        // types. So, instead of int, Integer type
        // array will be used
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Print the first kth largest elements
        for (int i = 0; i < k; i++)
            System.out.print(arr[i] + " ");
    }
 
    // This code is contributed by Niraj Dubey
    public static ArrayList<Integer> kLargest(int[] arr,
                                              int k)
    {
        // Convert using stream
        Integer[] obj_array
            = Arrays.stream(arr).boxed().toArray(
                Integer[] ::new);
        Arrays.sort(obj_array, Collections.reverseOrder());
        ArrayList<Integer> list = new ArrayList<>(k);
 
        for (int i = 0; i < k; i++)
            list.add(obj_array[i]);
 
        return list;
    }
 
      // Driver code
    public static void main(String[] args)
    {
        Integer arr[]
            = new Integer[] { 1, 23, 12, 9, 30, 2, 50 };
        int k = 3;
        kLargest(arr, k);
 
        // This code is contributed by Niraj Dubey
        // What if primitive datatype array is passed and
        // wanted to return in ArrayList<Integer>
        int[] prim_array = { 1, 23, 12, 9, 30, 2, 50 };
        kLargest(prim_array, k);
    }
}
// This code is contributed by Kamal Rawal

Python




''' Python3 code for k largest elements in an array'''
 
 
def kLargest(arr, k):
    # Sort the given array arr in reverse
    # order.
    arr.sort(reverse=True)
    # Print the first kth largest elements
    for i in range(k):
        print(arr[i], end=" ")
 
 
# Driver code
arr = [1, 23, 12, 9, 30, 2, 50]
# n = len(arr)
k = 3
kLargest(arr, k)
 
# This code is contributed by shreyanshi_arun.

C#




// C# code for k largest elements in an array
using System;
 
class GFG {
    public static void kLargest(int[] arr, int k)
    {
        // Sort the given array arr in reverse order
        // This method doesn't work with primitive data
        // types. So, instead of int, Integer type
        // array will be used
        Array.Sort(arr);
        Array.Reverse(arr);
 
        // Print the first kth largest elements
        for (int i = 0; i < k; i++)
            Console.Write(arr[i] + " ");
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr = new int[] { 1, 23, 12, 9, 30, 2, 50 };
        int k = 3;
        kLargest(arr, k);
    }
}
 
// This code contributed by Rajput-Ji

PHP




<?php
// PHP code for k largest
// elements in an array
 
function kLargest(&$arr, $n, $k)
{
    // Sort the given array arr
    // in reverse order.
    rsort($arr);
 
    // Print the first kth
    // largest elements
    for ($i = 0; $i < $k; $i++)
        echo $arr[$i] . " ";
}
 
// Driver Code
$arr = array(1, 23, 12, 9,
                30, 2, 50);
$n = sizeof($arr);
$k = 3;
kLargest($arr, $n, $k);
 
// This code is contributed
// by ChitraNayal
?>

Javascript




<script>
 
// JavaScript code for k largest
// elements in an array
 
function kLargest(arr, n, k)
{
    // Sort the given array arr in reverse
    // order.
    arr.sort((a, b) => b - a);
 
    // Print the first kth largest elements
    for (let i = 0; i < k; i++)
        document.write(arr[i] + " ");
}
 
// driver program
    let arr = [ 1, 23, 12, 9, 30, 2, 50 ];
    let n = arr.length;
    let k = 3;
    kLargest(arr, n, k);
 
 
// This code is contributed by Manoj.
 
</script>

Output

50 30 23 

Time complexity: O(N * log(N))
Auxiliary Space: O(1)

Complete Interview Preparation - GFG

Efficient Approaches: To solve the problem follow the below ideas: 

1. Using Max-Heap:

Follow the below steps to solve the problem:

  • Build a Max Heap
  • Use Extract Max K times to get K maximum elements from the Max Heap

Time complexity: O(N * log(N) + K * log(N)) 

2. Using order Statistics:

Follow the below steps to solve the problem:

  • Use an order statistic algorithm to find the Kth largest element. Please see the topic selection in worst-case linear time
  • Use the QuickSort Partition algorithm to partition around the Kth largest number
  • Sort the K-1 elements (elements greater than the Kth largest element)
    Note: This step is needed only if the sorted output is required

Time complexity: O(N) if we don’t need the sorted output, otherwise O(N + K * log(K))
Thanks to Shilpi for suggesting the first two approaches.

K largest(or smallest) elements in an array using Min-Heap:

To solve the problem follow the below idea:

We can create a Min-Heap of size K and then compare the root of the Min-Heap with other elements and if it is greater than the root, then swap the value of the root and heapify the heap. This will help us to get the K largest elements in the end

Follow the below steps to solve the problem:

  • Build a Min Heap MH of the first K elements (arr[0] to arr[K-1]) of the given array
  • For each element, after the Kth element (arr[K] to arr[N-1]), compare it with the root of MH
    • If the element is greater than the root then make it root and call heapify for MH 
    • Else ignore it
  • Finally, MH has the K largest elements, and the root of the MH is the Kth largest element

Note: All of the above methods can also be used to find the kth smallest elements

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Swap function to interchange
// the value of variables x and y
int swap(int& x, int& y)
{
    int temp = x;
    x = y;
    y = temp;
}
 
// Min Heap Class
// arr holds reference to an integer
// array size indicate the number of
// elements in Min Heap
class MinHeap {
 
    int size;
    int* arr;
 
public:
    // Constructor to initialize the size and arr
    MinHeap(int size, int input[]);
 
    // Min Heapify function, that assumes that
    // 2*i+1 and 2*i+2 are min heap and fix the
    // heap property for i.
    void heapify(int i);
 
    // Build the min heap, by calling heapify
    // for all non-leaf nodes.
    void buildHeap();
};
 
// Constructor to initialize data
// members and creating mean heap
MinHeap::MinHeap(int size, int input[])
{
    // Initializing arr and size
 
    this->size = size;
    this->arr = input;
 
    // Building the Min Heap
    buildHeap();
}
 
// Min Heapify function, that assumes
// 2*i+1 and 2*i+2 are min heap and
// fix min heap property for i
 
void MinHeap::heapify(int i)
{
    // If Leaf Node, Simply return
    if (i >= size / 2)
        return;
 
    // variable to store the smallest element
    // index out of i, 2*i+1 and 2*i+2
    int smallest;
 
    // Index of left node
    int left = 2 * i + 1;
 
    // Index of right node
    int right = 2 * i + 2;
 
    // Select minimum from left node and
    // current node i, and store the minimum
    // index in smallest variable
    smallest = arr[left] < arr[i] ? left : i;
 
    // If right child exist, compare and
    // update the smallest variable
    if (right < size)
        smallest
            = arr[right] < arr[smallest] ? right : smallest;
 
    // If Node i violates the min heap
    // property, swap  current node i with
    // smallest to fix the min-heap property
    // and recursively call heapify for node smallest.
    if (smallest != i) {
        swap(arr[i], arr[smallest]);
        heapify(smallest);
    }
}
 
// Build Min Heap
void MinHeap::buildHeap()
{
    // Calling Heapify for all non leaf nodes
    for (int i = size / 2 - 1; i >= 0; i--) {
        heapify(i);
    }
}
 
void FirstKelements(int arr[], int size, int k)
{
    // Creating Min Heap for given
    // array with only k elements
    MinHeap* m = new MinHeap(k, arr);
 
    // Loop For each element in array
    // after the kth element
    for (int i = k; i < size; i++) {
 
        // if current element is smaller
        // than minimum element, do nothing
        // and continue to next element
        if (arr[0] > arr[i])
            continue;
 
        // Otherwise Change minimum element to
        // current element, and call heapify to
        // restore the heap property
        else {
            arr[0] = arr[i];
            m->heapify(0);
        }
    }
    // Now min heap contains k maximum
    // elements, Iterate and print
    for (int i = 0; i < k; i++) {
        cout << arr[i] << " ";
    }
}
// Driver code
int main()
{
 
    int arr[]
        = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
 
    int size = sizeof(arr) / sizeof(arr[0]);
 
    // Size of Min Heap
    int k = 3;
 
    FirstKelements(arr, size, k);
 
    return 0;
}
// This code is contributed by Ankur Goel

Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class GFG {
 
    public static void FirstKelements(int arr[], int size,
                                      int k)
    {
 
        // Creating Min Heap for given
        // array with only k elements
        // Create min heap with priority queue
        PriorityQueue<Integer> minHeap
            = new PriorityQueue<>();
        for (int i = 0; i < k; i++) {
            minHeap.add(arr[i]);
        }
 
        // Loop For each element in array
        // after the kth element
        for (int i = k; i < size; i++) {
 
            // If current element is smaller
            // than minimum ((top element of
            // the minHeap) element, do nothing
            // and continue to next element
            if (minHeap.peek() > arr[i])
                continue;
 
            // Otherwise Change minimum element
            // (top element of the minHeap) to
            // current element by polling out
            // the top element of the minHeap
            else {
                minHeap.poll();
                minHeap.add(arr[i]);
            }
        }
 
        // Now min heap contains k maximum
        // elements, Iterate and print
        Iterator iterator = minHeap.iterator();
 
        while (iterator.hasNext()) {
            System.out.print(iterator.next() + " ");
        }
    }
 
    // Driver code
    public static void main(String[] args)
    {
        int arr[]
            = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
 
        int size = arr.length;
 
        // Size of Min Heap
        int k = 3;
 
        FirstKelements(arr, size, k);
    }
}
 
// This code is contributed by Vansh Sethi

Python3




# Python3 program for the above approach
 
# importing heapq module
# to implement heap
import heapq as hq
 
 
def FirstKelements(arr, size, k):
    # Creating Min Heap for given
    # array with only k elements
    # Create min heap using heapq module
    minHeap = []
 
    for i in range(k):
        minHeap.append(arr[i])
    hq.heapify(minHeap)
    # Loop For each element in array
    # after the kth element
 
    for i in range(k, size):
        # If current element is smaller
        # than minimum ((top element of
        # the minHeap) element, do nothing
        # and continue to next element
 
        if minHeap[0] > arr[i]:
            continue
        # Otherwise Change minimum element
        # (top element of the minHeap) to
        # current element by polling out
        # the top element of the minHeap
        else:
              # deleting top element of the min heap
            minHeap[0] = minHeap[-1]
            minHeap.pop()
            minHeap.append(arr[i])
            # maintaining heap again using
            # O(n) time operation....
            hq.heapify(minHeap)
    # Now min heap contains k maximum
    # elements, Iterate and print
    for i in minHeap:
        print(i, end=" ")
 
 
# Driver code
arr = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45]
size = len(arr)
# Size of Min Heap
k = 3
FirstKelements(arr, size, k)
'''Code is written by Rajat Kumar.....'''

C#




// C# program for the above approach
 
using System;
using System.Collections.Generic;
public class GFG {
 
    public static void FirstKelements(int[] arr, int size,
                                      int k)
    {
 
        // Creating Min Heap for given
        // array with only k elements
        // Create min heap with priority queue
        List<int> minHeap = new List<int>();
        for (int i = 0; i < k; i++) {
            minHeap.Add(arr[i]);
        }
 
        // Loop For each element in array
        // after the kth element
        for (int i = k; i < size; i++) {
            minHeap.Sort();
 
            // If current element is smaller
            // than minimum ((top element of
            // the minHeap) element, do nothing
            // and continue to next element
            if (minHeap[0] > arr[i])
                continue;
 
            // Otherwise Change minimum element
            // (top element of the minHeap) to
            // current element by polling out
            // the top element of the minHeap
            else {
                minHeap.RemoveAt(0);
                minHeap.Add(arr[i]);
            }
        }
 
        // Now min heap contains k maximum
        // elements, Iterate and print
        foreach(int i in minHeap)
        {
            Console.Write(i + " ");
        }
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        int[] arr
            = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
        int size = arr.Length;
 
        // Size of Min Heap
        int k = 3;
        FirstKelements(arr, size, k);
    }
}
 
// This code is contributed by aashish1995.

Javascript




<script>
    function FirstKelements(arr , size , k) {
 
        // Creating Min Heap for given
        // array with only k elements
        // Create min heap with priority queue
        var minHeap = [];
        for (var i = 0; i < k; i++) {
            minHeap.push(arr[i]);
        }
 
        // Loop For each element in array
        // after the kth element
        for (var i = k; i < size; i++) {
            minHeap.sort((a,b)=>a-b);
 
            // If current element is smaller
            // than minimum ((top element of
            // the minHeap) element, do nothing
            // and continue to next element
            if (minHeap[minHeap.length-3] > arr[i])
                continue;
 
            // Otherwise Change minimum element
            // (top element of the minHeap) to
            // current element by polling out
            // the top element of the minHeap
            else {
                minHeap.reverse();
                minHeap.pop();
                minHeap.reverse();
                minHeap.push(arr[i]);
            }
        }
 
        // Now min heap contains k maximum
        // elements, Iterate and print
        for (var iterator of minHeap) {
            document.write(iterator + " ");
        }
    }
 
    // Driver code
        var arr = [11, 3, 2, 1, 15, 5, 4,
                  45, 88, 96, 50, 45];
        var size = arr.length;
 
        // Size of Min Heap
        var k = 3;
        FirstKelements(arr, size, k);
 
// This code is contributed by gauravrajput1
</script>

Output

50 88 96 

Time Complexity: O(N * log K)
Auxiliary Space: O(K)

K largest(or smallest) elements in an array using Quick Sort partitioning algorithm:

To solve the problem follow the below idea:

We will find the pivot in the array until pivot element index is equal to K, because in the quick sort partioning algorithm all the elements less than pivot are on the left side of the pivot and greater than or equal to that are on the right side. So we can print the array (low to pivot to get K-smallest elements and (N-pivot_Index) to N for K-largest elements)

Follow the below steps to solve the problem:

  • Choose a pivot number
  • if K is lesser than the pivot_Index then repeat the step
  • if K is equal to pivot_Index: Print the array (low to pivot to get K-smallest elements and (n-pivot_Index) to n for K-largest elements)
  • if  K is greater than pivot_Index: Repeat the steps for the right part

Note: We can improve on the standard quicksort algorithm by using the random() function. Instead of using the pivot element as the last element, we can randomly choose the pivot element randomly.

Below is the implementation of the above approach:

C++




// c++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
int partition(int arr[], int l, int r);
 
// This function stops at K'th smallest element in arr[l..r]
// using QuickSort based method.
void kthSmallest(int arr[], int l, int r, int K, int N)
{
    // If k is smaller than number of elements in array
    if (K > 0 && K <= r - l + 1) {
 
        // Partition the array around last element and get
        // position of pivot element in sorted array
        int pos = partition(arr, l, r);
 
        // If position is same as k
        if (pos - l == K - 1)
            return;
 
        // If position is more, recur
        // for left subarray
        else if (pos - l > K - 1)
            return kthSmallest(arr, l, pos - 1, K, N);
 
        // Else recur for right subarray
        else
            return kthSmallest(arr, pos + 1, r,
                               K - pos + l - 1, N);
    }
 
    // If k is more than number of elements in array
    cout << "Invalid value of K";
}
 
void KthLargest(int arr[], int l, int r, int K, int N)
{
    // This function arranges k Largest elements in last k
    // positions It means it arranges N-K-1 smallest
    // elements from starting
 
    kthSmallest(arr, l, r, N - K - 1, N);
}
 
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
int partition(int arr[], int l, int r)
{
    int x = arr[r], i = l;
    for (int j = l; j <= r - 1; j++) {
        if (arr[j] <= x) {
            swap(&arr[i], &arr[j]);
            i++;
        }
    }
 
    swap(&arr[i], &arr[r]);
    return i;
}
 
// Driver code
int main()
{
    int arr[]
        = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    // Function call
 
    // For Smallest
    kthSmallest(arr, 0, N - 1, k, N);
 
    // Print KSmallest no.
    if (k >= 1 && k <= N) {
        cout << k << " largest elements are : ";
        for (int i = 0; i < k; i++)
            cout << arr[i] << "  ";
    }
 
    cout << endl;
 
    // For Largest
    KthLargest(arr, 0, N - 1, k, N);
 
    // Print KLargest no.
    if (k >= 1 && k <= N) {
        cout << k << " largest elements are : ";
        for (int i = N - 1; i >= N - k; i--)
            cout << arr[i] << "  ";
    }
    return 0;
}
 
// This code is contributed by shubhamm050402

C




// c program for the above approach
 
#include <stdio.h>
#include <stdlib.h>
 
// This function swaps values pointed by xp and yp
void swap(int* xp, int* yp)
{
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}
 
// picks up last element between start and end
int partition(int a[], int start, int end)
{
    // Selecting the pivot element
    int pivot = a[end];
    // Initially partition-index will be at starting
    int pIndex = start;
    for (int i = start; i < end; i++) {
        // If an element is lesser than pivot, swap it.
        if (a[i] <= pivot) {
            swap(&a[i], &a[pIndex]);
            // Incrementing pIndex for further swapping.
            pIndex++;
        }
    }
 
    // Lastly swapping or the correct position of pivot
    swap(&a[pIndex], &a[end]);
    return pIndex;
}
 
void kthSmallest(int arr[], int l, int r, int K, int N)
{
    // If k is smaller than number of elements in array
    if (K > 0 && K <= r - l + 1) {
 
        // Partition the array around last element and get
        // position of pivot element in sorted array
        int pos = partition(arr, l, r);
 
        // If position is same as k
        if (pos - l == K - 1)
            return;
 
        // If position is more, recur
        // for left subarray
        else if (pos - l > K - 1)
            return kthSmallest(arr, l, pos - 1, K, N);
 
        // Else recur for right subarray
        else
            return kthSmallest(arr, pos + 1, r,
                               K - pos + l - 1, N);
    }
 
    // If k is more than number of elements in array
    printf("Invalid value of K");
}
 
void KthLargest(int arr[], int l, int r, int K, int N)
{
    // This function arranges k Largest elements in last k
    // positions It means it arranges N-K-1 smallest
    // elements from starting
 
    kthSmallest(arr, l, r, N - K - 1, N);
}
 
// Driver Code
int main()
{
 
    int arr[]
        = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
 
    int N = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    // Function call
 
    // For Smallest
    kthSmallest(arr, 0, N - 1, k, N);
 
    // Print KSmallest no.
    if (k >= 1 && k <= N) {
        printf("%d smallest elements are : ", k);
        for (int i = 0; i < k; i++)
            printf("%d ", arr[i]);
    }
    printf("\n");
 
    // For Largest
    KthLargest(arr, 0, N - 1, k, N);
 
    // // Print KLargest no.
    if (k >= 1 && k <= N) {
        printf("%d largest elements are : ", k);
        for (int i = N - 1; i >= N - k; i--)
            printf("%d ", arr[i]);
    }
    return 0;
}
 
// This code is contributed by shubhamm050402

Java




// Java program for the above approach
 
import java.util.*;
 
class GFG {
 
    // Standard partition process of QuickSort.
    // It considers the last element as pivot
    // and moves all smaller element to left of
    // it and greater elements to right
    public static int partition(int arr[], int l, int r)
    {
        int x = arr[r], i = l;
        for (int j = l; j <= r - 1; j++) {
            if (arr[j] <= x) {
 
                // Swapping arr[i] and arr[j]
                int temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
 
                i++;
            }
        }
 
        // Swapping arr[i] and arr[r]
        int temp = arr[i];
        arr[i] = arr[r];
        arr[r] = temp;
 
        return i;
    }
 
    // This function stops at k'th smallest element
    // in arr[l..r] using QuickSort based method.
 
    public static void kthSmallest(int arr[], int l, int r,
                                   int K, int N)
    {
        // If k is smaller than number of elements
        // in array
        if (K > 0 && K <= r - l + 1) {
 
            // Partition the array around last
            // element and get position of pivot
            // element in sorted array
            int pos = partition(arr, l, r);
 
            // If position is same as k
            if (pos - l == K - 1)
                return;
 
            // If position is more, recur for
            // left subarray
            if (pos - l > K - 1)
                kthSmallest(arr, l, pos - 1, K, N);
 
            // Else recur for right subarray
            else
                kthSmallest(arr, pos + 1, r,
                            K - pos + l - 1, N);
        }
        else {
            // If k is more than number of elements
            // in array
            System.out.print("Invalid value of K");
        }
    }
 
    public static void kthLargest(int arr[], int l, int r,
                                  int K, int N)
    {
        // This function arranges k Largest elements in last
        // k positions
        // It means it arranges N-K-1 smallest elements from
        // starting
 
        kthSmallest(arr, l, r, N - K - 1, N);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[]
            = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
        int n = a.length;
 
        int low = 0;
        int high = n - 1;
 
        // Lets assume k is 3
        int k = 3;
 
        // Function call
 
        // For Smallest
        kthSmallest(a, 0, n - 1, k, n);
 
        // Print KSmallest no.
        if (k >= 1 && k <= n) {
            System.out.print(k
                             + " smallest elements are : ");
            for (int i = 0; i < k; i++)
                System.out.print(a[i] + " ");
        }
        System.out.println();
 
        // For Largest
 
        kthLargest(a, 0, n - 1, k, n);
 
        // Print KLargest no.
        if (k >= 1 && k <= n) {
            System.out.print(k
                             + " largest elements are : ");
            for (int i = n - 1; i >= n - k; i--)
                System.out.print(a[i] + " ");
        }
    }
}
 
// This code is contributed by shubhamm050402

Python3




# Python3 program for the above approach
 
import random
 
 
def kthSmallest(arr, l, r, K, n):
 
    # If k is smaller than number of
    # elements in array
    if (K > 0 and K <= r - l + 1):
 
        # Partition the array around last
        # element and get position of pivot
        # element in sorted array
        pos = partition(arr, l, r)
 
        # If position is same as k
        if (pos - l == K - 1):
            return
        if (pos - l > K - 1):  # If position is more,
                              # recur for left subarray
            return kthSmallest(arr, l, pos - 1, K, n)
 
        # Else recur for right subarray
        return kthSmallest(arr, pos + 1, r,
                           K - pos + l - 1, n)
 
    # If k is more than number of
    # elements in array
    print("Invalid value of K")
 
 
def KthLargest(arr, l, r, K, N):
 
    # This function arranges k Largest elements in last k positions
    #   It means it arranges N-K-1 smallest elements from starting
 
    kthSmallest(arr, l, r, N - K - 1, N)
 
 
# Standard partition process of QuickSort().
# It considers the last element as pivot and
# moves all smaller element to left of it
# and greater elements to right
 
 
def partition(arr, l, r):
 
    x = arr[r]
    i = l
    for j in range(l, r):
        if (arr[j] <= x):
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
    arr[i], arr[r] = arr[r], arr[i]
    return i
 
 
# Driver code
a = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45]
n = len(a)
 
low = 0
high = n - 1
 
# assume k is 3
k = 3
 
#  Function call
 
#  For Smallest
kthSmallest(a, 0, n - 1, k, n)
 
#  Print KSmallest no.
if (k >= 1 and k <= n):
    print(str(k) + " smallest elements are :", end=" ")
    for i in range(k):
        print(a[i], end=" ")
    print()
 
 
#  For Largest
KthLargest(a, 0, n-1, k, n)
#  Print KLargest no.
if (k >= 1 and k <= n):
    print(str(k) + " largest elements are :", end=" ")
    for i in range(n - 1, n-k-1, -1):
        print(a[i], end=" ")
 
 
# This code is contributed by shubhamm050402

C#




// c# program for the above approach
 
using System;
using System.Text;
 
public class GFG {
 
    // Standard partition process of QuickSort.
    // It considers the last element as pivot
    // and moves all smaller element to left of
    // it and greater elements to right
    public static int partition(int[] arr, int l, int r)
    {
        int x = arr[r], i = l;
        int temp = 0;
        for (int j = l; j <= r - 1; j++) {
 
            if (arr[j] <= x) {
                // Swapping arr[i] and arr[j]
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
 
                i++;
            }
        }
 
        // Swapping arr[i] and arr[r]
        temp = arr[i];
        arr[i] = arr[r];
        arr[r] = temp;
 
        return i;
    }
 
    // This function stops at k'th smallest
    // element in arr[l..r] using QuickSort
    // based method.
    public static void kthSmallest(int[] arr, int l, int r,
                                   int K, int N)
    {
        // If k is smaller than number
        // of elements in array
        if (K > 0 && K <= r - l + 1) {
            //  Console.Write(K);
            // Partition the array around last
            // element and get position of pivot
            // element in sorted array
            int pos = partition(arr, l, r);
 
            // If position is same as k
            if (pos - l == K - 1)
                return;
 
            // If position is more, recur for
            // left subarray
            else if (pos - l > K - 1)
                kthSmallest(arr, l, pos - 1, K, N);
 
            // Else recur for right subarray
            else
                kthSmallest(arr, pos + 1, r,
                            K - pos + l - 1, N);
        }
        else {
 
            // If k is more than number
            // of elements in array
            Console.Write("Invalid value of K");
            return;
        }
    }
 
    public static void kthLargest(int[] arr, int l, int r,
                                  int K, int N)
    {
        // This function arranges k Largest elements in last
        // k positions
        // It means it arranges N-K-1 smallest elements from
        // starting
 
        kthSmallest(arr, l, r, N - K - 1, N);
    }
 
    // Driver Code
    public static void Main(String[] args)
    {
        int[] a
            = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
        int n = a.Length;
        // Lets assume k is 3
        int k = 3;
 
        // Function call
 
        // For Smallest
        kthSmallest(a, 0, n - 1, k, n);
 
        // Print KSmallest no.
        if (k >= 1 && k <= n) {
            Console.Write(k + " smallest elements are : ");
            for (int i = 0; i < k; i++) {
                Console.Write(a[i] + " ");
            }
        }
 
        Console.WriteLine();
 
        // For Largest
        kthLargest(a, 0, n - 1, k, n);
 
        // Print KLargest no.
        if (k >= 1 && k <= n) {
            Console.Write(k + " largest elements are : ");
            for (int i = n - 1; i >= n - k; i--)
                Console.Write(a[i] + " ");
        }
    }
}
 
// This code is contributed by shubhamm050402

Javascript




<script>
  
 
    // Standard partition process of QuickSort.
    // It considers the last element as pivot
    // and moves all smaller element to left of
    // it and greater elements to right
    function partition( arr , l , r)
    {
        var x = arr[r], i = l;
        for (j = l; j <= r - 1; j++) {
            if (arr[j] <= x) {
                // Swapping arr[i] and arr[j]
                var temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
 
                i++;
            }
        }
 
        // Swapping arr[i] and arr[r]
        var temp = arr[i];
        arr[i] = arr[r];
        arr[r] = temp;
 
        return i;
    }
 
    // This function stops at k'th smallest element
    // in arr[l..r] using QuickSort based method.
    function kthSmallest( arr , l , r , k,n) {
        // If k is smaller than number of elements
        // in array
        if (k > 0 && k <= r - l + 1) {
            // Partition the array around last
            // element and get position of pivot
            // element in sorted array
            var pos = partition(arr, l, r);
 
            // If position is same as k
            if (pos - l == k - 1)
                return;
 
            // If position is more, recur for
            // left subarray
            if (pos - l > k - 1)
                return kthSmallest(arr, l, pos - 1, k,n);
 
            // Else recur for right subarray
            return kthSmallest(arr, pos + 1, r,
            k - pos + l - 1,n);
        }
 
        // If k is more than number of elements
        // in array
     
        document.write("Invalid value of K");
    }
     
     
    function KthLargest(arr , l , r , k,n)
{
    // This function arranges k Largest elements in last k positions
    // It means it arranges N-K-1 smallest elements from starting
     
    kthSmallest( arr , l , r , k,n);
}
 
 
    // Driver program to test above methods
     
        var arr = [ 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45];
        // Lets assume k is 3
        var k =3;
        var n = arr.length;
 
           
       // Function call
 
       // For Smallest
       kthSmallest(arr, 0,n-1, k,n);
 
       // Print KSmallest no.
       if (k >=1 && k <= n){
        document.write(k+ " smallest elements are : ");
       
        for (let i = 0; i < k; i++)
         document.write(arr[i]+" ");
       }
        
        document.write("<br/>");
 
        // For Largest
        KthLargest(arr, 0,n-1, k,n);
 
        // Print KLargest no.
         
        if (k >=1 && k <= n){
         document.write(k+ " largest elements are : ");
          
         for (var i = n - 1; i >= n - k; i--)
          document.write(arr[i]+ "  ");
       }
       
   
 
// This code is contributed by shubhamm050402
 
</script>

Output

3 smallest elements are : 3  2  1  
3 largest elements are : 96  50  88  

Time Complexity: O(N log N)
Auxiliary Space: O(1)

K largest(or smallest) elements in an array using priority queue library:

To solve the problem follow the below idea:

Priority queue can be used in the Min-Heap method above to get the K largest or smallest elements

Follow the below steps to solve the problem:

  • Push the first K elements into the priority queue from the array
  • After comparing the top of the priority queue with the current array element, we will pop the element at the top of priority_queue and insert the element.
  • In the case of the K largest element, the priority_queue will be in increasing order, and thus top most element will be the smallest so we are removing it
  • Similarly, in the case of the K smallest element, the priority_queue is in decreasing order and hence the topmost element is the largest one so we will remove it
  • In this fashion whole array is traversed and the priority queue of size K is printed which contains the K largest/smallest elements

Below is the implementation of the above approach:

C++




// C++ code for k largest/ smallest elements in an array
#include <bits/stdc++.h>
using namespace std;
 
// Function to find k largest array element
void kLargest(vector<int>& v, int N, int K)
{
    // Implementation using
    // a Priority Queue
    priority_queue<int, vector<int>, greater<int> > pq;
 
    for (int i = 0; i < N; ++i) {
 
        // Insert elements into
        // the priority queue
        pq.push(v[i]);
 
        // If size of the priority
        // queue exceeds k
        if (pq.size() > K) {
            pq.pop();
        }
    }
 
    // Print the k largest element
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }
    cout << endl;
}
 
// Function to find k smallest array element
void kSmalest(vector<int>& v, int N, int K)
{
    // Implementation using
    // a Priority Queue
    priority_queue<int> pq;
 
    for (int i = 0; i < N; ++i) {
 
        // Insert elements into
        // the priority queue
        pq.push(v[i]);
 
        // If size of the priority
        // queue exceeds k
        if (pq.size() > K) {
            pq.pop();
        }
    }
 
    // Print the k smallest element
    while (!pq.empty()) {
        cout << pq.top() << " ";
        pq.pop();
    }
}
 
// driver program
int main()
{
    // Given array
    vector<int> arr
        = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
    // Size of array
    int n = arr.size();
    int k = 3;
    cout << k << " largest elements are : ";
    kLargest(arr, n, k);
    cout << k << " smallest elements are : ";
    kSmalest(arr, n, k);
}
 
// This code is contributed by Pushpesh Raj.

Java




// Java code for k largest/ smallest elements in an array
import java.util.*;
 
class GFG {
 
    // Function to find k largest array element
    static void kLargest(int a[], int n, int k)
    {
        // Implementation using
        // a Priority Queue
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>();
 
        for (int i = 0; i < n; ++i) {
 
            // Insert elements into
            // the priority queue
            pq.add(a[i]);
 
            // If size of the priority
            // queue exceeds k
            if (pq.size() > k) {
                pq.poll();
            }
        }
 
        // Print the k largest element
        while (!pq.isEmpty()) {
            System.out.print(pq.peek() + " ");
            pq.poll();
        }
        System.out.println();
    }
 
    // Function to find k smallest array element
    static void kSmallest(int a[], int n, int k)
    {
        // Implementation using
        // a Priority Queue
        PriorityQueue<Integer> pq
            = new PriorityQueue<Integer>(
                Collections.reverseOrder());
 
        for (int i = 0; i < n; ++i) {
 
            // Insert elements into
            // the priority queue
            pq.add(a[i]);
 
            // If size of the priority
            // queue exceeds k
            if (pq.size() > k) {
                pq.poll();
            }
        }
 
        // Print the k largest element
        while (!pq.isEmpty()) {
            System.out.print(pq.peek() + " ");
            pq.poll();
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int a[]
            = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 };
        int n = a.length;
        int k = 3;
        System.out.print(k + " largest elements are : ");
        // Function Call
        kLargest(a, n, k);
        System.out.print(k + " smallest elements are : ");
        // Function Call
        kSmallest(a, n, k);
    }
}
 
// This code is contributed by Aarti_Rathi

Python3




# Python code for k largest/ smallest elements in an array
import heapq
 
# Function to find k largest array element
 
 
def kLargest(v, N, K):
 
    # Implementation using
    # a Priority Queue
    pq = []
    heapq.heapify(pq)
 
    for i in range(N):
 
        # Insert elements into
        # the priority queue
        heapq.heappush(pq, v[i])
 
        # If size of the priority
        # queue exceeds k
        if (len(pq) > K):
            heapq.heappop(pq)
 
    # Print the k largest element
    while(len(pq) != 0):
        print(heapq.heappop(pq), end=' ')
    print()
 
 
# Function to find k smallest array element
def kSmalest(v,  N, K):
 
    # Implementation using
    # a Priority Queue
    pq = []
 
    for i in range(N):
 
        # Insert elements into
        # the priority queue
        heapq.heappush(pq, -1*v[i])
 
        # If size of the priority
        # queue exceeds k
        if (len(pq) > K):
            heapq.heappop(pq)
 
    # Print the k largest element
    while(len(pq) != 0):
        print(heapq.heappop(pq)*-1, end=' ')
    print()
 
 
# driver program
 
# Given array
arr = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45]
# Size of array
n = len(arr)
k = 3
print(k, " largest elements are : ", end='')
kLargest(arr, n, k)
print(k, " smallest elements are : ", end='')
kSmalest(arr, n, k)
 
 
# This code is contributed by Abhijeet Kumar(abhijeet19403)

Output

3 largest elements are : 50 88 96 
3 smallest elements are : 3 2 1 

Time Complexity: O(N * log(K))
Auxiliary Space: O(K)

K largest(or smallest) elements in an array by creating a BST and Getting K greatest Elements:

To solve the problem follow the below idea:

We can create a BST of the given array elements and then print the K greatest/smallest elements

Follow the below steps to solve the problem:

  • We will create a Binary Search Tree
  • Then traverse the BST in reverse inorder fashion for K times
  • Print the K largest elements

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};
 
class Tree {
public:
    Node* root = NULL;
    void addNode(int data)
    {
        Node* newNode = new Node();
        newNode->data = data;
        if (!root) {
            root = newNode;
        }
        else {
            Node* cur = root;
            while (cur) {
                if (cur->data > data) {
                    if (cur->left) {
                        cur = cur->left;
                    }
                    else {
                        cur->left = newNode;
                        return;
                    }
                }
                else {
                    if (cur->right) {
                        cur = cur->right;
                    }
                    else {
                        cur->right = newNode;
                        return;
                    }
                }
            }
        }
    }
    void printGreatest(int& K, vector<int>& sol, Node* node)
    {
        if (!node || K == 0)
            return;
        printGreatest(K, sol, node->right);
        if (K <= 0)
            return;
        sol.push_back(node->data);
        K--;
        printGreatest(K, sol, node->left);
    }
};
 
class Solution {
public:
    vector<int> kLargest(int arr[], int n, int k)
    {
        vector<int> sol;
        Tree tree = Tree();
        for (int i = 0; i < n; i++) {
            tree.addNode(arr[i]);
        }
        tree.printGreatest(k, sol, tree.root);
        return sol;
    }
};
 
// Driver code
int main()
{
    int n = 5, k = 2;
    int arr[] = { 12, 5, 787, 1, 23 };
    Solution ob;
    auto ans = ob.kLargest(arr, n, k);
    cout << "Top " << k << " Elements: ";
    for (auto x : ans) {
        cout << x << " ";
    }
    cout << "\n";
    return 0;
}

Java




// Java program for the above approach
 
import java.io.*;
import java.util.*;
 
class Node {
    int data;
    Node left;
    Node right;
}
 
class Tree {
    Node root = null;
 
    void addNode(int data)
    {
        Node newNode = new Node();
        newNode.data = data;
        if (root == null) {
            root = newNode;
        }
        else {
            Node cur = root;
            while (cur != null) {
                if (cur.data > data) {
                    if (cur.left != null) {
                        cur = cur.left;
                    }
                    else {
                        cur.left = newNode;
                        return;
                    }
                }
                else {
                    if (cur.right != null) {
                        cur = cur.right;
                    }
                    else {
                        cur.right = newNode;
                        return;
                    }
                }
            }
        }
    }
    void printGreatest(int K, List<Integer> sol, Node node)
    {
        if (node == null || K == 0) {
            return;
        }
        printGreatest(K, sol, node.right);
        if (K <= 0) {
            return;
        }
        sol.add(node.data);
        K--;
        printGreatest(K, sol, node.left);
    }
}
 
class Solution {
    List<Integer> kLargest(int[] arr, int n, int k)
    {
        List<Integer> sol = new ArrayList<>();
        Tree tree = new Tree();
        for (int i = 0; i < n; i++) {
            tree.addNode(arr[i]);
        }
        tree.printGreatest(k, sol, tree.root);
        return sol;
    }
}
 
class GFG {
   
      // Driver code
    public static void main(String[] args)
    {
        int n = 5, k = 2;
        int[] arr = { 12, 5, 787, 1, 23 };
        Solution ob = new Solution();
        var ans = ob.kLargest(arr, n, k);
        System.out.print("Top " + k + " Element: ");
        for (int i = 0; i < 2; i++) {
            System.out.print(ans.get(i) + " ");
        }
        System.out.println();
    }
}
 
// This code is contributed by lokesh.

Output

Top 2 Elements: 787 23 

Time Complexity: O(N * log(N)) + O(K) ~= O(N * log(N)) (here making of Binary Search Tree from array take n*log(n) time + O(n) time for finding top k element)
Auxiliary Space: O(N) (to store the tree with N nodes we need O(N) space + O(K) space for storing the top K element to print)

Please write comments if you find any of the above explanations/algorithms incorrect, or find better ways to solve the same problem.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!