K largest elements in an array using Sorting

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

Output
50 30 23 

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

Print K largest(or smallest) elements in an array

Given an array arr[] of size N, the task is to printing K largest elements in an array.
Note: Elements in output 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

Similar Reads

K largest elements in an array using Sorting:

Sort the input array in descending order so that the first K elements in the array are the K largest elements...

K largest elements in an array using Binary Search:

The idea is to find the Kth largest element of the array and then print all the elements which are greater than or equal to Kth largest Element. The Kth largest element can be found using binary search by defining a search range based on the minimum and maximum values in the input array. In each iteration of binary search, count the larger than the midpoint and update the search range accordingly. This process continues until the range collapses to a single element, which is the kth largest element....

K largest elements in an array using Quick Sort partitioning algorithm:

This is an optimization over method 1, if QuickSort is used as a sorting algorithm in first step. In QuickSort, pick a pivot element, then move the pivot element to its correct position and partition the surrounding array. The idea is, not to do complete quicksort, but stop at the point where pivot itself is k’th largest element. Also, not to recur for both left and right sides of pivot, but recur for one of them according to the position of pivot....

K largest elements in an array using Priority Queue(Min-Heap):

The intuition behind this approach is to maintain a minheap (priority queue) of size K while iterating through the array. Doing this ensures that the min heap always contains the K largest elements encountered so far. If the size of the min heap exceeds K, remove the smallest element this step ensures that the heap maintains the K largest elements encountered so far. In the end, the min heap contains the K largest elements of the array....