Open In App

Sort elements by frequency

Last Updated : 04 Mar, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

Given an array of integers arr[], sort the array according to the frequency of elements, i.e. elements that have higher frequency comes first. If the frequencies of two elements are the same, then the smaller number comes first.

Examples:  

Input: arr[] = [5, 5, 4, 6, 4]
Output: [4, 4, 5, 5, 6]
Explanation: The highest frequency here is 2. Both 5 and 4 have that frequency. Now since the frequencies are the same the smaller element comes first. So 4 comes first then comes 5. Finally comes 6. The output is 4 4 5 5 6.

Input: arr[] = [9, 9, 9, 2, 5]
Output: [9, 9, 9, 2, 5]
Explanation: The highest frequency here is 3. Element 9 has the highest frequency So 9 comes first. Now both 2 and 5 have the same frequency. So we print smaller elements first. The output is 9 9 9 2 5.

Using Sorting - O(n * log n) Time and O(n) Space

The idea is to use sorting to arrange the similar elements together, the count frequencies using linear traversal. Store frequencies and items in a 2d array of elements. Finally sort this 2d array according to the frequency of each element.

Illustration

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

Step1: Sort the array, 
After sorting we get: 2 2 5 5 6 8 8 8

Step 2: Now construct the 2D array to maintain the count of every element as {freq, element}
{{2, 2}, {2, 5}, {1, 6}, {3, 8}}

Step 3: Sort the array by count
{{3, 8}, {2, 2}, {2, 5}, {1, 6}}

Set 4: Construct the result array by taking taking the second element and its count as first element
ans[] = {8, 8, 8, 2, 2, 5, 5, 6}

CPP
#include <bits/stdc++.h>
using namespace std;

// Function to sort the array 
// according to frequency of elements
vector<int> sortByFreq(vector<int> &arr) {
    int n = arr.size();

    // sort the array first
    sort(arr.begin(), arr.end());

    // create a 2d vector to store 
    // the frequency of each element
    vector<vector<int>> freq;

    // to sort the frequency in descending order
    auto comp = [&](vector<int> &a, vector<int> &b)
    {
        if (a[0] == b[0])
            return a[1] < b[1];
        return a[0] > b[0];
    };

    for(int i = 0; i < n; i++) {

        // to store the frequency
        int cnt = 1;
        while(i < n - 1 && arr[i] == arr[i + 1]) {
            cnt++;
            i++;
        }

        // push the frequency and the element
        freq.push_back({cnt, arr[i]});
    }
    
    // sort the frequency array
    sort(freq.begin(), freq.end(), comp);

    // to store the answer
    vector<int> ans;

    // push the elements in the answer array
    for(int i = 0; i < freq.size(); i++) {
        for(int j = 0; j < freq[i][0]; j++) {
            ans.push_back(freq[i][1]);
        }
    }
    return ans;
}

int main() {
    vector<int> arr = {5, 5, 4, 6, 4};
    vector<int> ans = sortByFreq(arr);
    for(int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}
Java
// Function to sort the array 
// according to frequency of elements
import java.util.*;

class GfG {

    // Function to sort the array 
    // according to frequency of elements
    static ArrayList<Integer> sortByFreq(int[] arr) {
        int n = arr.length;
        
        // sort the array first
        Arrays.sort(arr);
        
        // create a 2d vector to store 
        // the frequency of each element
        ArrayList<ArrayList<Integer>> freq = new ArrayList<>();
        
        // to sort the frequency in descending order
        Comparator<ArrayList<Integer>> comp = 
            new Comparator<ArrayList<Integer>>() {
            public int compare(ArrayList<Integer> a, 
                ArrayList<Integer> b) {
                if(a.get(0).equals(b.get(0)))
                    return a.get(1) - b.get(1);
                return b.get(0) - a.get(0);
            }
        };
        
        for (int i = 0; i < n; i++) {
            
            // to store the frequency
            int cnt = 1;
            while(i < n - 1 && arr[i] == arr[i + 1]) {
                cnt++;
                i++;
            }
            
            // push the frequency and the element
            ArrayList<Integer> temp = new ArrayList<>();
            temp.add(cnt);
            temp.add(arr[i]);
            freq.add(temp);
        }
        
        // sort the frequency array
        Collections.sort(freq, comp);
        
        // to store the answer
        ArrayList<Integer> ans = new ArrayList<>();
        
        // push the elements in the answer array
        for (int i = 0; i < freq.size(); i++) {
            int count = freq.get(i).get(0);
            int value = freq.get(i).get(1);
            for (int j = 0; j < count; j++) {
                ans.add(value);
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        int[] arr = {5, 5, 4, 6, 4};
        ArrayList<Integer> ans = sortByFreq(arr);
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
Python
# Function to sort the array 
# according to frequency of elements
def sortByFreq(arr):
    n = len(arr)
    
    # sort the array first
    arr.sort()
    
    # create a 2d vector to store 
    # the frequency of each element
    freq = []
    
    # to sort the frequency in descending order
    i = 0
    while i < n:
        cnt = 1
        while i < n - 1 and arr[i] == arr[i + 1]:
            cnt += 1
            i += 1
        freq.append([cnt, arr[i]])
        i += 1
    
    freq.sort(key=lambda a: (-a[0], a[1]))
    
    # to store the answer
    ans = []
    
    # push the elements in the answer array
    for i in range(len(freq)):
        for j in range(freq[i][0]):
            ans.append(freq[i][1])
    return ans

if __name__ == "__main__":
    arr = [5, 5, 4, 6, 4]
    ans = sortByFreq(arr)
    for i in ans:
        print(i, end=" ")
C#
// Function to sort the array 
// according to frequency of elements
using System;
using System.Collections.Generic;
using System.Linq;

class GfG {

    // Function to sort the array 
    // according to frequency of elements
    static List<int> sortByFreq(int[] arr) {
        int n = arr.Length;
        
        // sort the array first
        Array.Sort(arr);
        
        // create a 2d vector to store 
        // the frequency of each element
        List<List<int>> freq = new List<List<int>>();
        
        // to sort the frequency in descending order
        for (int i = 0; i < n; i++) {
            int cnt = 1;
            while (i < n - 1 && arr[i] == arr[i + 1]) {
                cnt++;
                i++;
            }
            freq.Add(new List<int> { cnt, arr[i] });
        }
        
        freq.Sort((a, b) => {
            if(a[0] == b[0])
                return a[1].CompareTo(b[1]);
            return b[0].CompareTo(a[0]);
        });
        
        // to store the answer
        List<int> ans = new List<int>();
        
        // push the elements in the answer array
        for (int i = 0; i < freq.Count; i++) {
            int count = freq[i][0];
            int value = freq[i][1];
            for (int j = 0; j < count; j++) {
                ans.Add(value);
            }
        }
        return ans;
    }
    
    static void Main() {
        int[] arr = {5, 5, 4, 6, 4};
        List<int> ans = sortByFreq(arr);
        foreach (int i in ans) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// Function to sort the array 
// according to frequency of elements
function sortByFreq(arr) {
    
    // sort the array first
    arr.sort((a, b) => a - b);
    
    // create a 2d vector to store 
    // the frequency of each element
    let freq = [];
    let n = arr.length;
    
    for (let i = 0; i < n; i++) {
        let cnt = 1;
        while (i < n - 1 && arr[i] === arr[i + 1]) {
            cnt++;
            i++;
        }
        freq.push([cnt, arr[i]]);
    }
    
    // to sort the frequency in descending order
    freq.sort((a, b) => {
        if (a[0] === b[0])
            return a[1] - b[1];
        return b[0] - a[0];
    });
    
    // to store the answer
    let ans = [];
    
    // push the elements in the answer array
    for (let i = 0; i < freq.length; i++) {
        for (let j = 0; j < freq[i][0]; j++) {
            ans.push(freq[i][1]);
        }
    }
    return ans;
}
 
let arr = [5, 5, 4, 6, 4];
let ans = sortByFreq(arr);
console.log(ans.join(" "));

Output
4 4 5 5 6 

Using Hashing and Sorting - O(n * log n) Time and O(n) Space

In the above approach we are firstly sorting the given array to create the frequency array, but instead of doing so, we can use Hash Map or Dictionary. The idea is to store the count of each element in a Hash Map, and then create the frequency array similar to above approach.

CPP
#include <bits/stdc++.h>
using namespace std;

// Function to sort the array 
// according to frequency of elements
vector<int> sortByFreq(vector<int> &arr) {
    int n = arr.size();

    // hash map to store the 
    // frequency of each element
    unordered_map<int, int> mp;

    // store the frequency of each element
    for(int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }

    // create a 2d vector to store 
    // the frequency of each element
    vector<vector<int>> freq;

    // to sort the frequency in descending order
    auto comp = [&](vector<int> &a, vector<int> &b)
    {
        if (a[0] == b[0])
            return a[1] < b[1];
        return a[0] > b[0];
    };

    // store the frequency and the element
    for(auto i : mp) {
        freq.push_back({i.second, i.first});
    }
    
    // sort the frequency array
    sort(freq.begin(), freq.end(), comp);

    // to store the answer
    vector<int> ans;

    // push the elements in the answer array
    for(int i = 0; i < freq.size(); i++) {
        for(int j = 0; j < freq[i][0]; j++) {
            ans.push_back(freq[i][1]);
        }
    }
    return ans;
}

int main() {
    vector<int> arr = {5, 5, 4, 6, 4};
    vector<int> ans = sortByFreq(arr);
    for(int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}
Java
// Function to sort the array 
// according to frequency of elements
import java.util.*;

class GfG {

    // Function to sort the array 
    // according to frequency of elements
    static ArrayList<Integer> sortByFreq(int[] arr) {
        int n = arr.length;
        
        // hash map to store the 
        // frequency of each element
        HashMap<Integer, Integer> mp = new HashMap<>();
        
        // store the frequency of each element
        for (int i = 0; i < n; i++) {
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
        
        // create a 2d vector to store 
        // the frequency of each element
        ArrayList<ArrayList<Integer>> freq = new ArrayList<>();
        
        // store the frequency and the element
        for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
            ArrayList<Integer> temp = new ArrayList<>();
            temp.add(entry.getValue());
            temp.add(entry.getKey());
            freq.add(temp);
        }
        
        // to sort the frequency in descending order
        Collections.sort(freq, new Comparator<ArrayList<Integer>>() {
            public int compare(ArrayList<Integer> a, ArrayList<Integer> b) {
                if(a.get(0).equals(b.get(0)))
                    return a.get(1) - b.get(1);
                return b.get(0) - a.get(0);
            }
        });
        
        // to store the answer
        ArrayList<Integer> ans = new ArrayList<>();
        
        // push the elements in the answer array
        for (int i = 0; i < freq.size(); i++) {
            int count = freq.get(i).get(0);
            int value = freq.get(i).get(1);
            for (int j = 0; j < count; j++) {
                ans.add(value);
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        int[] arr = {5, 5, 4, 6, 4};
        ArrayList<Integer> ans = sortByFreq(arr);
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
Python
# Function to sort the array 
# according to frequency of elements
def sortByFreq(arr):
    n = len(arr)
    
    # hash map to store the 
    # frequency of each element
    mp = {}
    
    # store the frequency of each element
    for i in range(n):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    
    # create a 2d vector to store 
    # the frequency of each element
    freq = []
    
    # store the frequency and the element
    for key, value in mp.items():
        freq.append([value, key])
    
    # to sort the frequency in descending order
    freq.sort(key=lambda a: (-a[0], a[1]))
    
    # to store the answer
    ans = []
    
    # push the elements in the answer array
    for i in range(len(freq)):
        for j in range(freq[i][0]):
            ans.append(freq[i][1])
    return ans

if __name__ == "__main__":
    arr = [5, 5, 4, 6, 4]
    ans = sortByFreq(arr)
    for i in range(len(ans)):
        print(ans[i], end=" ")
C#
// Function to sort the array 
// according to frequency of elements
using System;
using System.Collections.Generic;

class GfG {

    // Function to sort the array 
    // according to frequency of elements
    static List<int> sortByFreq(int[] arr) {
        int n = arr.Length;
        
        // hash map to store the 
        // frequency of each element
        Dictionary<int, int> mp = new Dictionary<int, int>();
        
        // store the frequency of each element
        for (int i = 0; i < n; i++) {
            if (mp.ContainsKey(arr[i]))
                mp[arr[i]]++;
            else
                mp[arr[i]] = 1;
        }
        
        // create a 2d vector to store 
        // the frequency of each element
        List<List<int>> freq = new List<List<int>>();
        
        // store the frequency and the element
        foreach (var kvp in mp) {
            List<int> temp = new List<int> { kvp.Value, kvp.Key };
            freq.Add(temp);
        }
        
        // to sort the frequency in descending order
        freq.Sort((a, b) => {
            if(a[0] == b[0])
                return a[1].CompareTo(b[1]);
            return b[0].CompareTo(a[0]);
        });
        
        // to store the answer
        List<int> ans = new List<int>();
        
        // push the elements in the answer array
        for (int i = 0; i < freq.Count; i++) {
            int count = freq[i][0];
            int value = freq[i][1];
            for (int j = 0; j < count; j++) {
                ans.Add(value);
            }
        }
        return ans;
    }
    
    static void Main() {
        int[] arr = {5, 5, 4, 6, 4};
        List<int> ans = sortByFreq(arr);
        foreach (int i in ans) {
            Console.Write(i + " ");
        }
    }
}
JavaScript
// Function to sort the array 
// according to frequency of elements
function sortByFreq(arr) {
    
    // hash map to store the 
    // frequency of each element
    let mp = {};
    let n = arr.length;
    
    // store the frequency of each element
    for (let i = 0; i < n; i++) {
        if (mp.hasOwnProperty(arr[i]))
            mp[arr[i]]++;
        else
            mp[arr[i]] = 1;
    }
    
    // create a 2d vector to store 
    // the frequency of each element
    let freq = [];
    for (let key in mp) {
        freq.push([mp[key], parseInt(key)]);
    }
    
    // to sort the frequency in descending order
    freq.sort((a, b) => {
        if(a[0] === b[0])
            return a[1] - b[1];
        return b[0] - a[0];
    });
    
    // to store the answer
    let ans = [];
    
    // push the elements in the answer array
    for (let i = 0; i < freq.length; i++) {
        for (let j = 0; j < freq[i][0]; j++) {
            ans.push(freq[i][1]);
        }
    }
    return ans;
}
 
let arr = [5, 5, 4, 6, 4];
let ans = sortByFreq(arr);
console.log(ans.join(" "));

Output
4 4 5 5 6 

Using Binary Search Tree and Sorting - O(n * log n) Time and O(n) Space

The idea is to store the elements in the form of BST, and if an element in already present then increment the count of the corresponding node. Thereafter store the element and its frequency in a 2d array and sort it based on the frequency. This approach has been discussed in article Sort elements by frequency using BST

Using Hash Map and Heap - O(n * log n) Time and O(n) Space

The idea is to firstly create the value - frequency table using the Hash Map, then make a Heap such that high frequency remains at top.

Follow the given steps to solve the problem:

  • Take the array and use Hash Map to create value - frequency table
  • Then make a heap such that high frequency remains at top and when frequency is same, just keep in ascending order.
  • Store the negative of element in a heap, to make sure that the elements with same frequency are sorted in ascending order.
  • Then after full insertion into Heap, pop one by one and store it into the array.

Below is the implementation of the above approach:

C++
#include <bits/stdc++.h>
using namespace std;

// Function to sort the array 
// according to frequency of elements
vector<int> sortByFreq(vector<int> &arr) {
    int n = arr.size();

    // hash map to store the 
    // frequency of each element
    unordered_map<int, int> mp;

    // store the frequency of each element
    for(int i = 0; i < n; i++) {
        mp[arr[i]]++;
    }

    // to store the frequency 
    // in descending order
    priority_queue<vector<int>> pq;

    // store the frequency and the element
    for(auto i : mp) {

        // storing the negative of element
        // to sor the elements with same
        // frequency in ascending order
        pq.push({i.second, -i.first});
    }

    // to store the answer
    vector<int> ans;

    // push the elements in the answer array
    while(!pq.empty()) {
        int freq = pq.top()[0];
        int ele = -pq.top()[1];
        pq.pop();
        for(int i = 0; i < freq; i++) {
            ans.push_back(ele);
        }
    }

    return ans;
}

int main() {
    vector<int> arr = {5, 5, 4, 6, 4};
    vector<int> ans = sortByFreq(arr);
    for(int i = 0; i < ans.size(); i++) {
        cout << ans[i] << " ";
    }
    return 0;
}
Java
// Function to sort the array 
// according to frequency of elements
import java.util.*;

class GfG {

    // Function to sort the array 
    // according to frequency of elements
    static ArrayList<Integer> sortByFreq(int[] arr) {
        int n = arr.length;
        
        // hash map to store the 
        // frequency of each element
        HashMap<Integer, Integer> mp = new HashMap<>();
        
        // store the frequency of each element
        for (int i = 0; i < n; i++) {
            mp.put(arr[i], mp.getOrDefault(arr[i], 0) + 1);
        }
        
        // to store the frequency 
        // in descending order
        PriorityQueue<int[]> pq = new PriorityQueue<>(
            new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                if (a[0] == b[0])
                    return a[1] - b[1];
                return b[0] - a[0];
            }
        });
        
        // store the frequency and the element
        for (Map.Entry<Integer, Integer> entry : mp.entrySet()) {
            int ele = entry.getKey();
            int freq = entry.getValue();
            
            // storing the negative of element
            // to sort the elements with same
            // frequency in ascending order
            pq.add(new int[]{freq, -ele});
        }
        
        // to store the answer
        ArrayList<Integer> ans = new ArrayList<>();
        
        // push the elements in the answer array
        while (!pq.isEmpty()) {
            int[] top = pq.poll();
            int freq = top[0];
            int ele = -top[1];
            for (int i = 0; i < freq; i++) {
                ans.add(ele);
            }
        }
        return ans;
    }
    
    public static void main(String[] args) {
        int[] arr = {5, 5, 4, 6, 4};
        ArrayList<Integer> ans = sortByFreq(arr);
        for (int i = 0; i < ans.size(); i++) {
            System.out.print(ans.get(i) + " ");
        }
    }
}
Python
# Function to sort the array 
# according to frequency of elements
import heapq

def sortByFreq(arr):
    n = len(arr)
    
    # hash map to store the 
    # frequency of each element
    mp = {}
    
    # store the frequency of each element
    for i in range(n):
        if arr[i] in mp:
            mp[arr[i]] += 1
        else:
            mp[arr[i]] = 1
    
    # to store the frequency 
    # in descending order
    pq = []
    
    # store the frequency and the element
    for key, freq in mp.items():
        # storing the negative of element
        # to sort the elements with same
        # frequency in ascending order
        heapq.heappush(pq, (-freq, key));
    
    # to store the answer
    ans = []
    
    # push the elements in the answer array
    while pq:
        freq, ele = heapq.heappop(pq)
        freq = -freq
        for i in range(freq):
            ans.append(ele)
    return ans

if __name__ == "__main__":
    arr = [5, 5, 4, 6, 4]
    ans = sortByFreq(arr)
    for i in range(len(ans)):
        print(ans[i], end=" ")
JavaScript
// Function to sort the array 
// according to frequency of elements
function sortByFreq(arr) {
    
    // hash map to store the 
    // frequency of each element
    let mp = {};
    let n = arr.length;
    
    // store the frequency of each element
    for (let i = 0; i < n; i++) {
        if (mp.hasOwnProperty(arr[i]))
            mp[arr[i]]++;
        else
            mp[arr[i]] = 1;
    }
    
    // to store the frequency 
    // in descending order
    let pq = [];
    
    // store the frequency and the element
    for (let key in mp) {
        let freq = mp[key];
        // storing the negative of element
        // to sort the elements with same
        // frequency in ascending order
        pq.push([freq, -parseInt(key)]);
    }
    
    pq.sort((a, b) => {
        if(a[0] === b[0])
            return a[1] - b[1];
        return b[0] - a[0];
    });
    
    // to store the answer
    let ans = [];
    
    // push the elements in the answer array
    while (pq.length > 0) {
        let top = pq.shift();
        let freq = top[0];
        let ele = -top[1];
        for (let i = 0; i < freq; i++) {
            ans.push(ele);
        }
    }
    return ans;
}
 
let arr = [5, 5, 4, 6, 4];
let ans = sortByFreq(arr);
console.log(ans.join(" "));

Output
4 4 5 5 6 

Next Article
Article Tags :
Practice Tags :

Similar Reads