Sorting element of an array by frequency in decreasing order

Given an array arr[] of N integers. The task is to sort the array arr[] according to the frequency of elements in decreasing order.
Note: If the frequencies of the two elements are the same, then the smaller element should come first.

Examples:

Input: arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }
Output: 4 4 4 2 2 5 5 6 8

Input: arr[] = { 9, 9, 5, 8, 5 }
Output: 5 5 9 9 8

Approach:



  1. Store the frequency of all element in array arr[].
    For arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 }
    The frequency array of the above array is:
    freq[] = { 0, 0, 2, 0, 3, 2, 0, 1, 0, 1}
    
  2. Traverse the frequency array and for all the element having frequency greater than 1, update the value in the array arr[] as:

    freq[2] = 2
    arr[0] = 100000*freq[2] + (100000 – 2) = 299998

    freq[4] = 3
    arr[1] = 100000*freq[2] + (100000 – 4) = 399996

    freq[5] = 2
    arr[2] = 100000*freq[2] + (100000 – 5) = 299995

    freq[6] = 2
    arr[3] = 100000*freq[2] + (100000 – 6) = 199994

    freq[8] = 2
    arr[4] = 100000*freq[2] + (100000 – 2) = 199994

    Now array becomes:
    arr[] = {299998, 399996, 299995, 199994, 199992, 2, 2, 8, 5}

  3. Sort the array arr[] in decreasing order.
  4. Traverse the array arr[] and to get the element and frequency of that element as per the updation of array element in step 2, do the following:

    To get the frequency of current element:
    frequency = arr[i]/100000;
    To get the value:
    value = 100000 – arr[i]%100000

    For Example:

    if arr[i] = 399996
    frequency = arr[i]/100000 = 399996/100000 = 3
    value = 100000 – arr[i]%100000 = 100000 – 99996 = 4
    The element 4 is having frequency 3.

  5. For each element in arr[] find the value and frequency(say f) at each index and print the value f number of times.

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to sort an array in
// decreasing order of their frequnecy
#include "bits/stdc++.h"
using namespace std;
  
// Function that return the index
// upto all the array elements are
// updated.
int sortByFreq(int* arr, int n)
{
  
    // Initialise maxE = -1
    int maxE = -1;
  
    // Find the maximum element of
    // arr[]
    for (int i = 0; i < n; i++) {
        maxE = max(maxE, arr[i]);
    }
  
    // Create frequency array freq[]
    int freq[maxE + 1] = { 0 };
  
    // Update the frequency array as
    // per the occurence of element in
    // arr[]
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
  
    // Initialise cnt to 0
    int cnt = 0;
  
    // Traversing freq[]
    for (int i = 0; i <= maxE; i++) {
  
        // If freq of an element is
        // greater than 0 update the
        // value of arr[] at index cnt
        // & increment cnt
        if (freq[i] > 0) {
  
            int value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt++;
        }
    }
  
    // Return cnt
    return cnt;
}
  
// Function that print array arr[]
// elements in sorted order
void printSortedArray(int* arr, int cnt)
{
  
    // Traversing arr[] till index cnt
    for (int i = 0; i < cnt; i++) {
  
        // Find frequency of elements
        int frequency = arr[i] / 100000;
  
        // Find value at index i
        int value = 100000 - (arr[i] % 100000);
  
        // Traversing till frequency
        // to print value at index i
        for (int j = 0; j < frequency; j++) {
            cout << value << ' ';
        }
    }
}
  
// Driver code
int main()
{
  
    int arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
  
    // Size of array arr[]
    int n = sizeof(arr) / sizeof(arr[0]);
  
    // Function call to get cnt
    int cnt = sortByFreq(arr, n);
  
    // Sort the arr[] in decreasing order
    sort(arr, arr + cnt, greater<int>());
  
    // Function that prints elements
    // in decreasing order
    printSortedArray(arr, cnt);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to sort an array in
// decreasing order of their frequnecy
import java.util.*;
  
class GFG{
   
// Function that return the index
// upto all the array elements are
// updated.
static int sortByFreq(Integer []arr, int n)
{
   
    // Initialise maxE = -1
    int maxE = -1;
   
    // Find the maximum element of
    // arr[]
    for (int i = 0; i < n; i++) {
        maxE = Math.max(maxE, arr[i]);
    }
   
    // Create frequency array freq[]
    int freq[] = new int[maxE + 1];
   
    // Update the frequency array as
    // per the occurence of element in
    // arr[]
    for (int i = 0; i < n; i++) {
        freq[arr[i]]++;
    }
   
    // Initialise cnt to 0
    int cnt = 0;
   
    // Traversing freq[]
    for (int i = 0; i <= maxE; i++) {
   
        // If freq of an element is
        // greater than 0 update the
        // value of arr[] at index cnt
        // & increment cnt
        if (freq[i] > 0) {
   
            int value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt++;
        }
    }
   
    // Return cnt
    return cnt;
}
   
// Function that print array arr[]
// elements in sorted order
static void printSortedArray(Integer []arr, int cnt)
{
   
    // Traversing arr[] till index cnt
    for (int i = 0; i < cnt; i++) {
   
        // Find frequency of elements
        int frequency = arr[i] / 100000;
   
        // Find value at index i
        int value = 100000 - (arr[i] % 100000);
   
        // Traversing till frequency
        // to print value at index i
        for (int j = 0; j < frequency; j++) {
            System.out.print(value + " ");
        }
    }
}
   
// Driver code
public static void main(String[] args)
{
   
    Integer arr[] = { 4, 4, 5, 6, 4, 2, 2, 8, 5 };
   
    // Size of array arr[]
    int n = arr.length;
   
    // Function call to get cnt
    int cnt = sortByFreq(arr, n);
   
    // Sort the arr[] in decreasing order
    Arrays.sort(arr, Collections.reverseOrder());
   
    // Function that prints elements
    // in decreasing order
    printSortedArray(arr, cnt);
   
}
}
  
// This code is contributed by sapnasingh4991

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to sort an array in
# decreasing order of their frequnecy
  
# Function that return the index
# upto all the array elements are
# updated.
def sortByFreq(arr, n):
  
    # Initialise maxE = -1
    maxE = -1;
  
    # Find the maximum element of
    # arr[]
    for i in range(n):
        maxE = max(maxE, arr[i])
  
    # Create frequency array freq[]
    freq = [0]*(maxE + 1);
  
    # Update the frequency array as
    # per the occurence of element in
    # arr[]
    for i in range(n):
        freq[arr[i]] += 1;
      
    # Initialise cnt to 0
    cnt = 0;
  
    # Traversing freq[]
    for i in range(maxE+1):
  
        # If freq of an element is
        # greater than 0 update the
        # value of arr[] at index cnt
        # & increment cnt
        if (freq[i] > 0):
  
            value = 100000 - i;
            arr[cnt] = 100000 * freq[i] + value;
            cnt += 1;
          
    # Return cnt
    return cnt;
  
# Function that print array arr[]
# elements in sorted order
def printSortedArray(arr, cnt):
  
    # Traversing arr[] till index cnt
    for i in range(cnt):
  
        # Find frequency of elements
        frequency = arr[i] / 100000;
  
        # Find value at index i
        value = 100000 - (arr[i] % 100000);
  
        # Traversing till frequency
        # to print value at index i
        for j in range(int(frequency)):
            print(value, end=" ")
              
# Driver code
if __name__=='__main__'
  
    arr = [ 4, 4, 5, 6, 4, 2, 2, 8, 5 ]
  
    # Size of array arr[]
    n = len(arr)
  
    # Function call to get cnt
    cnt = sortByFreq(arr, n);
  
    # Sort the arr[] in decreasing order
    arr.sort(reverse = True)
  
    # Function that prints elements
    # in decreasing order
    printSortedArray(arr, cnt);
  
# This code is contributed by Princi Singh

chevron_right


Output:

4 4 4 2 2 5 5 6 8

Time Complexity: O(N*log N)
Auxillary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Recommended Posts:


Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.