Sort elements by frequency
Last Updated :
23 Jul, 2025
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(" "));
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(" "));
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(" "));
Sort elements by frequency
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem