Sort elements by frequency
Last Updated :
30 May, 2024
Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first
Examples:
Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6}
Input: arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}
Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}
Sort elements by frequency using sorting:
Follow the given steps to solve the problem:
- Use a sorting algorithm to sort the elements
- Iterate the sorted array and construct a 2D array of elements and count
- Sort the 2D array according to the count
Below is the illustration of the above approach:
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
{{2, 2}, {5, 2}, { 6, 1}, {8, 3}}
Step 3: Sort the array by count
{{8, 3}, {2, 2}, {5, 2}, {6, 1}}
How to maintain the order of elements if the frequency is the same?
The above approach doesn’t make sure the order of elements remains the same if the frequency is the same. To handle this, we should use indexes in step 3, if two counts are the same then we should first process(or print) the element with a lower index. In step 1, we should store the indexes instead of elements.
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
indexes: 0 2 1 4 5 3 6 7
Step 2: Now construct the 2D array to maintain the count of every element as
Index, Count
0, 2
1, 2
5, 1
3, 3
Step 3: Sort the array by count (consider indexes in case of tie)
{{3, 3}, {0, 2}, {1, 2}, {5, 1}}
Print the elements using indexes in the above 2D array
Below is the implementation of the above approach:
CPP
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
// Used for sorting
struct ele {
int count, index, val;
};
// Used for sorting by value
bool mycomp(struct ele a, struct ele b)
{
return (a.val < b.val);
}
// Used for sorting by frequency. And if frequency is same,
// then by appearance
bool mycomp2(struct ele a, struct ele b)
{
if (a.count != b.count)
return (a.count < b.count);
else
return a.index > b.index;
}
void sortByFrequency(int arr[], int n)
{
struct ele element[n];
for (int i = 0; i < n; i++) {
// Fill Indexes
element[i].index = i;
// Initialize counts as 0
element[i].count = 0;
// Fill values in structure
// elements
element[i].val = arr[i];
}
/* Sort the structure elements according to value,
we used stable sort so relative order is maintained.
*/
stable_sort(element, element + n, mycomp);
/* initialize count of first element as 1 */
element[0].count = 1;
/* Count occurrences of remaining elements */
for (int i = 1; i < n; i++) {
if (element[i].val == element[i - 1].val) {
element[i].count += element[i - 1].count + 1;
/* Set count of previous element as -1, we are
doing this because we'll again sort on the
basis of counts (if counts are equal than on
the basis of index)*/
element[i - 1].count = -1;
/* Retain the first index (Remember first index
is always present in the first duplicate we
used stable sort. */
element[i].index = element[i - 1].index;
}
/* Else If previous element is not equal to current
so set the count to 1 */
else
element[i].count = 1;
}
/* Now we have counts and first index for each element
so now sort on the basis of count and in case of tie
use index to sort.*/
stable_sort(element, element + n, mycomp2);
for (int i = n - 1, index = 0; i >= 0; i--)
if (element[i].count != -1)
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
// Driver code
int main()
{
int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Java
// Java program to sort elements by frequency. If two
// elements have same count, then put the elements that
// appears first Importing required classes
import java.util.*;
class ele {
int count, index, val;
}
// Used for sorting by value
class mycomp implements Comparator<ele> {
public int compare(ele a, ele b)
{
return (a.val - b.val);
}
}
// Used for sorting by frequency. And if frequency is same,
// then by appearance
class mycomp2 implements Comparator<ele> {
public int compare(ele a, ele b)
{
if (a.count != b.count)
return (a.count - b.count);
return (b.index - a.index);
}
}
class GFG {
static void sortByFrequency(int[] arr, int n)
{
ArrayList<ele> element = new ArrayList<ele>();
// ele[] element = new ele[n];
for (int i = 0; i < n; i++) {
element.add(new ele());
// Fill Indexes
element.get(i).index = i;
// Initialize counts as 0
element.get(i).count = 0;
// Fill values in structure
// elements
element.get(i).val = arr[i];
}
/* Sort the structure elements according to value,
we used stable sort so relative order is
maintained.
*/
Collections.sort(element, new mycomp());
/* initialize count of first element as 1 */
element.get(0).count = 1;
/* Count occurrences of remaining elements */
for (int i = 1; i < n; i++) {
if (element.get(i).val == element.get(i - 1).val) {
element.get(i).count += element.get(i - 1).count + 1;
/* Set count of previous element as -1, we
are doing this because we'll again sort
on the basis of counts (if counts are
equal than on the basis of index)*/
element.get(i - 1).count = -1;
/* Retain the first index (Remember first
index is always present in the first
duplicate we used stable sort. */
element.get(i).index = element.get(i - 1).index;
}
/* Else If previous element is not equal to
current so set the count to 1 */
else
element.get(i).count = 1;
}
/* Now we have counts and first index for each
element so now sort on the basis of count and in
case of tie use index to sort.*/
Collections.sort(element, new mycomp2());
for (int i = n - 1, index = 0; i >= 0; i--){
if (element.get(i).count != -1)
{
for (int j = 0; j < element.get(i).count;j++)
arr[index++] = element.get(i).val;
}
}
}
// Driver code
public static void main(String[] args)
{
int[] arr = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = arr.length;
// Function call
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
Python
# Python3 program that performs the following
# operations: Sort elements by frequency. If two elements
# have same count, then put the elements that appears first
# Used for sorting
class ele:
def __init__(self):
self.count = 0
self.index = 0
self.val = 0
def mycomp(a):
return a.val
# Used for sorting by frequency. And if frequency is same,
# then by appearance
def mycomp2(a):
# using negative value for a.index
# since the sorting should be in
# descending order
return (a.count, -a.index)
def sortByFrequency(arr, n):
element = [None for _ in range(n)]
for i in range(n):
element[i] = ele()
# Fill Indexes
element[i].index = i
# Initialize counts as 0
element[i].count = 0
# Fill values in structure
# elements
element[i].val = arr[i]
# Sort the structure elements according to value,
# we used stable sort so relative order is maintained.
#
element.sort(key=mycomp)
# initialize count of first element as 1
element[0].count = 1
# Count occurrences of remaining elements
for i in range(1, n):
if (element[i].val == element[i - 1].val):
element[i].count += element[i - 1].count + 1
# Set count of previous element as -1, we are
# doing this because we'll again sort on the
# basis of counts (if counts are equal than on
# the basis of index)*/
element[i - 1].count = -1
# Retain the first index (Remember first index
# is always present in the first duplicate we
# used stable sort. */
element[i].index = element[i - 1].index
# Else If previous element is not equal to current
# so set the count to 1
else:
element[i].count = 1
# Now we have counts and first index for each element
# so now sort on the basis of count and in case of tie
# use index to sort.*/
element.sort(key=mycomp2)
index = 0
for i in range(n - 1, -1, -1):
if (element[i].count != -1):
for j in range(element[i].count):
arr[index] = element[i].val
index += 1
# Driver code
arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
n = len(arr)
# Function call
sortByFrequency(arr, n)
print(*arr)
# This code is contributed by phasing17
C#
// Sort elements by frequency. If two elements have same
// count, then put the elements that appears first
using System;
using System.Collections.Generic;
// Used for sorting
class ele {
public int count, index, val;
};
// Used for sorting by value
class mycomp : Comparer<ele> {
public override int Compare(ele a, ele b)
{
return (a.val.CompareTo(b.val));
}
};
// Used for sorting by frequency. And if frequency is same,
// then by appearance
class mycomp2 : Comparer<ele> {
public override int Compare(ele a, ele b)
{
if (a.count != b.count)
return (a.count).CompareTo(b.count);
return (b.index).CompareTo(a.index);
}
};
class GFG {
static void sortByFrequency(int[] arr, int n)
{
ele[] element = new ele[n];
for (int i = 0; i < n; i++) {
element[i] = new ele();
// Fill Indexes
element[i].index = i;
// Initialize counts as 0
element[i].count = 0;
// Fill values in structure
// elements
element[i].val = arr[i];
}
/* Sort the structure elements according to value,
we used stable sort so relative order is
maintained.
*/
Array.Sort(element, new mycomp());
/* initialize count of first element as 1 */
element[0].count = 1;
/* Count occurrences of remaining elements */
for (int i = 1; i < n; i++) {
if (element[i].val == element[i - 1].val) {
element[i].count
+= element[i - 1].count + 1;
/* Set count of previous element as -1, we
are doing this because we'll again sort
on the basis of counts (if counts are
equal than on the basis of index)*/
element[i - 1].count = -1;
/* Retain the first index (Remember first
index is always present in the first
duplicate we used stable sort. */
element[i].index = element[i - 1].index;
}
/* Else If previous element is not equal to
current so set the count to 1 */
else
element[i].count = 1;
}
/* Now we have counts and first index for each
element so now sort on the basis of count and in
case of tie use index to sort.*/
Array.Sort(element, new mycomp2());
for (int i = n - 1, index = 0; i >= 0; i--)
if (element[i].count != -1)
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
// Driver code
public static void Main(string[] args)
{
int[] arr = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = arr.Length;
// Function call
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by phasing17
JavaScript
// JavaScript program that performs the following
// operations: Sort elements by frequency. If two elements
// have same count, then put the elements that appears first
// Used for sorting
class ele
{
constructor()
{
this.count = 0
this.index = 0
this.val = 0
}
}
function mycomp(a, b)
{
return a.val - b.val
}
// Used for sorting by frequency. And if frequency is same,
// then by appearance
function mycomp2(a, b)
{
// using negative value for a.index
// since the sorting should be in
// descending order
if (a.count == b.count)
return b.index - a.index
return a.count - b.count
}
function sortByFrequency(arr, n)
{
let element = new Array(n)
for (var i = 0; i < n; i++)
{
element[i] = new ele()
// Fill Indexes
element[i].index = i
// Initialize counts as 0
element[i].count = 0
// Fill values in structure
// elements
element[i].val = arr[i]
}
// Sort the structure elements according to value,
// we used stable sort so relative order is maintained.
//
element.sort(mycomp)
// initialize count of first element as 1
element[0].count = 1
// Count occurrences of remaining elements
for (var i = 1; i < n; i++)
{
if (element[i].val == element[i - 1].val)
{
element[i].count += element[i - 1].count + 1
// Set count of previous element as -1, we are
// doing this because we'll again sort on the
// basis of counts (if counts are equal than on
// the basis of index)*/
element[i - 1].count = -1
// Retain the first index (Remember first index
// is always present in the first duplicate we
// used stable sort. */
element[i].index = element[i - 1].index
}
// Else If previous element is not equal to current
// so set the count to 1
else
element[i].count = 1
}
// Now we have counts and first index for each element
// so now sort on the basis of count and in case of tie
// use index to sort.*/
element.sort(mycomp2)
let index = 0
for (var i = n - 1; i >= 0; i--)
if (element[i].count != -1)
for (var j = 0; j < element[i].count; j++)
{
arr[index] = element[i].val
index += 1
}
}
// Driver code
let arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
let n = arr.length
// Function call
sortByFrequency(arr, n)
console.log(arr.join(" "))
// This code is contributed by phasing17
Output8 8 8 2 2 5 5 6 -1 9999999
Time Complexity: O(N log N), where the N is the size of the array
Auxiliary Space: O(N)
Thanks to Gaurav Ahirwar for providing the above implementation
Sort elements by frequency using hashing and sorting:
To solve the problem follow the below idea:
Using a hashing mechanism, we can store the elements (also the first index) and their counts in a hash. Finally, sort the hash elements according to their counts
Below is the implementation of the above approach:
CPP
// CPP program for above approach
#include <bits/stdc++.h>
using namespace std;
// Compare function
bool fcompare(pair<int, pair<int, int> > p,
pair<int, pair<int, int> > p1)
{
if (p.second.second != p1.second.second)
return (p.second.second > p1.second.second);
else
return (p.second.first < p1.second.first);
}
void sortByFrequency(int arr[], int n)
{
unordered_map<int, pair<int, int> > hash; // hash map
for (int i = 0; i < n; i++) {
if (hash.find(arr[i]) != hash.end())
hash[arr[i]].second++;
else
hash[arr[i]] = make_pair(i, 1);
} // store the count of all the elements in the hashmap
// Iterator to Traverse the Hashmap
auto it = hash.begin();
// Vector to store the Final Sortted order
vector<pair<int, pair<int, int> > > b;
for (it; it != hash.end(); ++it)
b.push_back(make_pair(it->first, it->second));
sort(b.begin(), b.end(), fcompare);
// Printing the Sorted sequence
for (int i = 0; i < b.size(); i++) {
int count = b[i].second.second;
while (count--)
cout << b[i].first << " ";
}
}
// Driver code
int main()
{
int arr[] = { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
// Function call
sortByFrequency(arr, n);
return 0;
}
Java
// Java program for above approach
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
class GFG {
static Integer[] arr
= { 2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8 };
// Driver Code
public static void main(String[] args)
{
List<Integer> list = Arrays.asList(arr);
// Function call
sortBasedOnFrequencyAndValue(list);
}
// Compare Function
public static void
sortBasedOnFrequencyAndValue(List<Integer> list)
{
int n = arr.length;
final HashMap<Integer, Integer> mapCount
= new HashMap<Integer, Integer>();
final HashMap<Integer, Integer> mapIndex
= new HashMap<Integer, Integer>();
for (int i = 0; i < n; i++) {
if (mapCount.containsKey(arr[i])) {
mapCount.put(arr[i],
mapCount.get(arr[i]) + 1);
}
else {
mapCount.put(
arr[i],
1); // Map to capture Count of elements
mapIndex.put(arr[i],
i); // Map to capture 1st
// occurrence of elements
}
}
Collections.sort(list, new Comparator<Integer>() {
public int compare(Integer n1, Integer n2)
{
int freq1 = mapCount.get(n1);
int freq2 = mapCount.get(n2);
if (freq1 != freq2) {
return freq2 - freq1;
}
else {
return mapIndex.get(n1)
- mapIndex.get(
n2); // Elements with Lesser
// Index gets Higher
// Priority
}
}
});
System.out.println(list);
}
}
Python
# Python3 program for above approach
from collections import defaultdict
# Sort by Frequency
def sortByFreq(arr, n):
# arr -> Array to be sorted
# n -> Length of Array
# d is a hashmap(referred as dictionary in python)
d = defaultdict(lambda: 0)
for i in range(n):
d[arr[i]] += 1
# Sorting the array 'arr' where key
# is the function based on which
# the array is sorted
# While sorting we want to give
# first priority to Frequency
# Then to value of item
arr.sort(key=lambda x: (-d[x], x), reverse = True)
#require Updation:- reverse = True, to sort an array in descending order (Jayesh Verma)
return (arr)
# Driver code
if __name__ == "__main__":
arr = [2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8]
n = len(arr)
# Function call
solution = sortByFreq(arr, n)
print(*solution)
C#
// C# program to implement the approach
using System;
using System.Collections.Generic;
public class GFG {
static int[] arr;
// Compare Function
public static void
sortBasedOnFrequencyAndValue(List<int> list)
{
int n = arr.Length;
Dictionary<int, int> mapCount
= new Dictionary<int, int>();
Dictionary<int, int> mapIndex
= new Dictionary<int, int>();
for (int i = 0; i < n; i++) {
if (mapCount.ContainsKey(arr[i])) {
mapCount[arr[i]]++;
}
else {
mapCount[arr[i]]
= 1; // Map to capture Count of elements
mapIndex[arr[i]]
= i; // Map to capture 1st occurrence of
// elements
}
}
list.Sort(
(int n1, int n2) => mapCount[n1] != mapCount[n2]
? mapCount[n2].CompareTo(mapCount[n1])
: mapIndex[n1].CompareTo(mapIndex[n2])
// Elements with Lesser
// Index gets Higher
// Priority
);
foreach(var i in list) Console.Write(i + " ");
}
// Driver Code
public static void Main(string[] args)
{
arr = new int[] { 2, 5, 2, 6, -1,
9999999, 5, 8, 8, 8 };
List<int> list = new List<int>(arr);
// Function call
sortBasedOnFrequencyAndValue(list);
}
}
// This code is contributed by phasing17
JavaScript
<script>
let arr=[2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8];
// Compare Function
function sortBasedOnFrequencyAndValue(list)
{
let n = arr.length;
let mapCount
= new Map();
let mapIndex
= new Map();
for (let i = 0; i < n; i++) {
if (mapCount.has(arr[i])) {
mapCount.set(arr[i],
mapCount.get(arr[i]) + 1);
}
else {
mapCount.set(arr[i],1); // Map to capture Count of elements
mapIndex.set(arr[i],i); // Map to capture 1st occurrence of elements
}
}
list.sort(function(n1,n2){
let freq1 = mapCount.get(n1);
let freq2 = mapCount.get(n2);
if (freq1 != freq2) {
return freq2 - freq1;
}
else {
return mapIndex.get(n1)
- mapIndex.get(
n2); // Elements with Lesser
// Index gets Higher
// Priority
}
});
document.write(list.join(" "));
}
// Driver Code
sortBasedOnFrequencyAndValue(arr);
// This code is contributed by patel2127
</script>
Output8 8 8 2 2 5 5 6 -1 9999999
Time Complexity: O(N log N), where the N is the size of the array
Auxiliary Space: O(N)
Note: This can also be solved by Using two maps, one for array element as an index and after this second map whose keys are frequency and value are array elements.
Sort elements by frequency using BST:
Follow the given steps to solve the problem:
- Insert elements in BST one by one and if an element is already present then increment the count of the node. The node of the Binary Search Tree (used in this approach) will be as follows.
C++
class tree {
public:
int element;
int first_index; /*To handle ties in counts*/
int count;
}
tree BST;
C
struct tree {
int element;
int first_index /*To handle ties in counts*/
int count;
} BST;
Java
static class tree {
int element;
int first_index; /*To handle ties in counts*/
int count;
}
tree BST = new tree();
// This code is contributed by gauravrajput1
Python
# Python code to implement the approach
class Tree:
element = None
# to handle ties
first_index = None
count = None
BST = Tree()
# This code is contributed by phasing17
C#
public class tree {
public int element;
public int first_index; /* To handle ties in counts */
public int count;
}
tree BST = new tree();
// This code is contributed by gauravrajput1
JavaScript
// JS code to implement the approach
class tree {
constructor()
{
this.element;
this.first_index; //To handle ties in counts
this.count;
}
};
// This code is contributed by phasing17
- Store the first indexes and corresponding counts of BST in a 2D array.
- Sort the 2D array according to counts (and use indexes in case of a tie).
Implementation of the this approach: Set 2
Time Complexity: O(N log N) if a Self Balancing Binary Search Tree is used.
Auxiliary Space: O(N)
Sort elements by frequency using Heap:
Follow the given steps to solve the problem:
- Take the arr and use unordered_map to have VALUE : FREQUENCY Table
- Then make a HEAP such that high frequency remains at TOP and when frequency is same, just keep in ascending order (Smaller at TOP)
- Then After full insertion into Heap
- Pop one by one and copy it into the Array
Below is the implementation of the above approach:
C++
// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
#define ppi pair<int, int>
/*IMPORTANT: comparator works in prority_queue only if they
are a class which has
operator() overloaded in it (got this from stackoverflow) */
class Compare {
public:
bool operator()(pair<int, int> a, pair<int, int> b)
{
// b is at top and a is at bottom - have that in
// mind
if (a.first == b.first) // when freq same
return a.second
> b.second; // smaller val stays at top
return a.first
< b.first; // higher freq stays at top
}
};
void solve(vector<int>& arr)
{
int N = arr.size();
unordered_map<int, int> mpp; // val, freq
for (int a : arr) {
mpp[a]++;
}
// max heap - as max wise freq elements is what needed
priority_queue<ppi, vector<ppi>, Compare> maxH;
for (auto m : mpp) {
maxH.push({ m.second, m.first }); // freq, val
}
// now the max freq is at TOP of MAX heap
int i = 0; // to maintain index to copy
while (maxH.size() > 0) {
int val = maxH.top().second; // val
int freq = maxH.top().first; // freq
while (freq--) {
// freq - those many times make a copy
arr[i] = val;
i++;
}
maxH.pop(); // heapify happens and next top freq ele
// goes up
}
}
// Driver code
int main()
{
vector<int> vec{ 2, 5, 2, 8, 5, 6, 8, 8 };
int n = vec.size();
// Function call
solve(vec);
for (int i = 0; i < n; i++)
cout << vec[i] << " ";
cout << "\n";
return 0;
}
// Code done by Balakrishnan R (rbkraj000)
Java
import java.util.*;
class Compare
implements Comparator<Map.Entry<Integer, Integer> > {
public int compare(Map.Entry<Integer, Integer> a,
Map.Entry<Integer, Integer> b)
{
// b is at top and a is at bottom - have that in
// mind
if (a.getValue() == b.getValue()) // when freq same
return a.getKey().compareTo(
b.getKey()); // smaller val stays at top
return b.getValue().compareTo(
a.getValue()); // higher freq stays at top
}
}
class Main {
static void solve(List<Integer> arr)
{
int N = arr.size();
Map<Integer, Integer> mpp
= new HashMap<>(); // val, freq
for (int a : arr) {
mpp.put(a, mpp.getOrDefault(a, 0) + 1);
}
// max heap - as max wise freq elements is what
// needed
PriorityQueue<Map.Entry<Integer, Integer> > maxH
= new PriorityQueue<>(new Compare());
for (Map.Entry<Integer, Integer> m :
mpp.entrySet()) {
maxH.add(m); // freq, val
}
// now the max freq is at TOP of MAX heap
int i = 0; // to maintain index to copy
while (maxH.size() > 0) {
int val = maxH.peek().getKey(); // val
int freq = maxH.peek().getValue(); // freq
while (freq-- > 0) {
// freq - those many times make a copy
arr.set(i, val);
i++;
}
maxH.poll(); // heapify happens and next top
// freq ele goes up
}
}
public static void main(String[] args)
{
List<Integer> arr
= Arrays.asList(2, 5, 2, 8, 5, 6, 8, 8);
int n = arr.size();
// Function call
solve(arr);
for (int i = 0; i < n; i++)
System.out.print(arr.get(i) + " ");
System.out.println();
}
}
// This code is contributed by divyansh2212
Python
from collections import defaultdict
from queue import PriorityQueue
class Compare:
def __init__(self, freq, val):
self.freq = freq
self.val = val
def __lt__(self, other):
if self.freq == other.freq:
return self.val < other.val
return self.freq > other.freq
def solve(arr):
n = len(arr)
mpp = defaultdict(int)
for a in arr:
mpp[a] += 1
max_heap = PriorityQueue()
for key, value in mpp.items():
max_heap.put(Compare(value, key))
i = 0
while not max_heap.empty():
item = max_heap.get()
freq = item.freq
val = item.val
for _ in range(freq):
arr[i] = val
i += 1
return arr
vec = [2, 5, 2, 8, 5, 6, 8, 8]
print(solve(vec))
C#
using System;
using System.Collections.Generic;
using System.Linq;
class KVCompare : IComparer<KeyValuePair<int, int> > {
public int Compare(KeyValuePair<int, int> a,
KeyValuePair<int, int> b)
{
// b is at top and a is at bottom - have that in
// mind
if (a.Value == b.Value) // when freq same
return a.Key.CompareTo(
b.Key); // smaller val stays at top
return b.Value.CompareTo(
a.Value); // higher freq stays at top
}
}
class GFG {
static void Solve(List<int> arr)
{
int n = arr.Count;
Dictionary<int, int> mpp
= new Dictionary<int, int>(); // val, freq
foreach(int a in arr)
{
if (mpp.ContainsKey(a))
mpp[a]++;
else
mpp[a] = 1;
}
// sorted list - as max wise freq elements is what
// needed
SortedList<KeyValuePair<int, int>, bool> maxH
= new SortedList<KeyValuePair<int, int>, bool>(
new KVCompare());
foreach(KeyValuePair<int, int> m in mpp)
{
maxH.Add(m, true); // freq, val
}
// now the max freq is at TOP of MAX heap
int i = 0; // to maintain index to copy
while (maxH.Count > 0) {
int val = maxH.Keys[0].Key; // val
int freq = maxH.Keys[0].Value; // freq
while (freq-- > 0) {
// freq - those many times make a copy
arr[i] = val;
i++;
}
maxH.RemoveAt(
0); // heapify happens and next top
// freq ele goes up
}
}
public static void Main(string[] args)
{
List<int> arr
= new List<int>() { 2, 5, 2, 8, 5, 6, 8, 8 };
int n = arr.Count;
// Function call
Solve(arr);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
}
// This code is contributed by phasing17
JavaScript
// Define the `solve` function
function solve(arr) {
// Find the length of the array
let N = arr.length;
// Create an empty map to store the frequency of each element in the array
let mpp = {};
// Loop through the array to count the frequency of each element
for (let i = 0; i < N; i++) {
if (mpp[arr[i]] === undefined) {
// If the element has not been encountered before, add it to the map with a frequency of 1
mpp[arr[i]] = 1;
} else {
// If the element has been encountered before, increment its frequency by 1
mpp[arr[i]]++;
}
}
// Create an empty array to store the frequency and value of each element
let maxH = [];
// Loop through the map to add the frequency and value of each element to the `maxH` array
for (let key in mpp) {
maxH.push([mpp[key], key]);
}
// Sort the `maxH` array in descending order of frequency, and ascending order of value if frequency is equal
maxH.sort((a, b) => {
if (a[0] === b[0]) {
return b[1] - a[1];
}
return a[0] - b[0];
});
// Initialize a variable `i` to 0
let i = 0;
// Loop through the sorted `maxH` array
while (maxH.length > 0) {
// Get the frequency and value of the current element
let freq = maxH[maxH.length - 1][0];
let val = maxH[maxH.length - 1][1];
// Fill the `arr` with the value `freq` times, starting from the `i`-th index
for (let j = 0; j < freq; j++) {
arr[i] = val;
i++;
}
// Remove the current element from the `maxH` array
maxH.pop();
}
}
// Test the function with an example array
let vec = [2, 5, 2, 8, 5, 6, 8, 8];
solve(vec);
console.log(vec);
// This code is contributed by Nayan Nand
The code and approach is done by Balakrishnan R.
Time Complexity: O(d * log(d)) (Dominating factor O(n + 2 * d * log (d))). O(n) (unordered map insertion- as 1 insertion takes O(1)) + O(d*log(d)) (Heap insertion – as one insertion is log N complexity) + O(d*log(d)) (Heap Deletion – as one pop takes Log N complexity)
Here d = No. of Distinct Elements, n = Total no. of elements (size of input array). (Always d<=n depends on the array)
Auxiliary Space: O(d), As heap and map is used
Sort elements by frequency using Quicksort:
Follow the given steps to solve the problem:
- Make a structure called “ele” with two fields called “val” and “count” to hold the value and count of each element in the input array.
- Make an array of “ele” structures of size n, where n is the size of the input array, and set the “val” field of each element to the value from the input array and the “count” field to 0.
- Traverse through the input array and for each element, increase the count field of the corresponding “ele” structure by 1.
- Using the quicksort method and a custom comparison function for elements, sort the “ele” array in decreasing order of count and rising order of value.
- Finally, recreate the input array by iterating over the sorted “ele” array in descending order of count and adding the value of each element to the input array count number of times equal to its count field.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct ele {
int val, count;
};
void swap(struct ele* a, struct ele* b)
{
struct ele temp = *a;
*a = *b;
*b = temp;
}
int partition(struct ele arr[], int low, int high)
{
struct ele pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j].count < pivot.count || (arr[j].count == pivot.count && arr[j].val > pivot.val)) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quicksort(struct ele arr[], int low, int high)
{
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
void sortByFrequency(int arr[], int n)
{
struct ele element[n];
for (int i = 0; i < n; i++) {
element[i].val = arr[i];
element[i].count = 0;
}
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
element[i].count++;
else
element[j].count++;
}
quicksort(element, 0, n - 1);
for (int i = n - 1, index = 0; i >= 0; i--) {
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
}
int main()
{
int arr[] = { 2, 5, 2, 8, 5, 6, 8, 8};
int n = sizeof(arr) / sizeof(arr[0]);
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
// This code is contributed by Vaibhav Saroj
Java
// Java code for the above approach
import java.util.Arrays;
public class GFG {
static class ele {
public int val;
public int count;
}
static void swap(ele[] arr, int i, int j) {
ele temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static int partition(ele[] arr, int low, int high) {
ele pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high - 1; j++) {
if (arr[j].count < pivot.count || (arr[j].count == pivot.count && arr[j].val > pivot.val)) {
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return i + 1;
}
static void quicksort(ele[] arr, int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
static void sortByFrequency(int[] arr, int n) {
ele[] element = new ele[n];
for (int i = 0; i < n; i++) {
element[i] = new ele();
element[i].val = arr[i];
element[i].count = 0;
}
for (int i = 0; i < n; i++) {
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
element[i].count++;
else
element[j].count++;
}
quicksort(element, 0, n - 1);
for (int i = n - 1, index = 0; i >= 0; i--) {
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
}
public static void main(String[] args) {
int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
int n = arr.length;
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
// This code is contributed by Pushpesh Raj
Python
def sortByFrequency(arr):
element = []
for i in range(len(arr)):
element.append({'val': arr[i], 'count': 0})
for i in range(len(arr)):
j = 0
while j < i:
if arr[i] == arr[j]:
break
j += 1
if i == j:
element[i]['count'] += 1
else:
element[j]['count'] += 1
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j]['count'] < pivot['count'] or (arr[j]['count'] == pivot['count'] and arr[j]['val'] > pivot['val']):
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quicksort(arr, low, high):
if low < high:
pi = partition(arr, low, high)
quicksort(arr, low, pi - 1)
quicksort(arr, pi + 1, high)
quicksort(element, 0, len(arr) - 1)
index = 0
for i in range(len(arr) - 1, -1, -1):
for j in range(element[i]['count']):
arr[index] = element[i]['val']
index += 1
return arr
arr = [2, 5, 2, 8, 5, 6, 8, 8]
sortedArr = sortByFrequency(arr)
print(sortedArr)
# by phasing17
C#
using System;
public class Program
{
struct ele
{
public int val;
public int count;
}
static void swap(ref ele a, ref ele b)
{
ele temp = a;
a = b;
b = temp;
}
static int partition(ele[] arr, int low, int high)
{
ele pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j].count < pivot.count || (arr[j].count == pivot.count && arr[j].val > pivot.val))
{
i++;
swap(ref arr[i], ref arr[j]);
}
}
swap(ref arr[i + 1], ref arr[high]);
return (i + 1);
}
static void quicksort(ele[] arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
static void sortByFrequency(int[] arr, int n)
{
ele[] element = new ele[n];
for (int i = 0; i < n; i++)
{
element[i].val = arr[i];
element[i].count = 0;
}
for (int i = 0; i < n; i++)
{
int j;
for (j = 0; j < i; j++)
if (arr[i] == arr[j])
break;
if (i == j)
element[i].count++;
else
element[j].count++;
}
quicksort(element, 0, n - 1);
for (int i = n - 1, index = 0; i >= 0; i--)
{
for (int j = 0; j < element[i].count; j++)
arr[index++] = element[i].val;
}
}
static void Main()
{
int[] arr = { 2, 5, 2, 8, 5, 6, 8, 8 };
int n = arr.Length;
sortByFrequency(arr, n);
for (int i = 0; i < n; i++)
Console.Write(arr[i] + " ");
}
}
// This code is contributed by Vaibhav Saroj
JavaScript
function sortByFrequency(arr) {
const element = [];
for (let i = 0; i < arr.length; i++) {
element[i] = { val: arr[i], count: 0 };
}
for (let i = 0; i < arr.length; i++) {
let j;
for (j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
break;
}
}
if (i == j) {
element[i].count++;
} else {
element[j].count++;
}
}
function swap(a, b) {
const temp = a;
a = b;
b = temp;
}
function partition(arr, low, high) {
const pivot = arr[high];
let i = low - 1;
for (let j = low; j <= high - 1; j++) {
if (
arr[j].count < pivot.count ||
(arr[j].count == pivot.count && arr[j].val > pivot.val)
) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
function quicksort(arr, low, high) {
if (low < high) {
const pi = partition(arr, low, high);
quicksort(arr, low, pi - 1);
quicksort(arr, pi + 1, high);
}
}
quicksort(element, 0, arr.length - 1);
for (let i = arr.length - 1, index = 0; i >= 0; i--) {
for (let j = 0; j < element[i].count; j++) {
arr[index++] = element[i].val;
}
}
return arr;
}
const arr = [2, 5, 2, 8, 5, 6, 8, 8];
const sortedArr = sortByFrequency(arr);
console.log(sortedArr);
// This code is contributed by Vaibhav Saroj
This Quicksort approach and code is contributed by Vaibhav Saroj.
Time complexity: O(n log n).
Space complexity: O(n).
Related Article: Sort elements by frequency | Set 2
Similar Reads
Sorting Algorithms
A Sorting Algorithm is used to rearrange a given array or list of elements in an order. Sorting is provided in library implementation of most of the programming languages. Basics of Sorting Algorithms:Introduction to Sorting Applications of Sorting Sorting Algorithms:Comparison Based : Selection Sor
3 min read
Introduction to Sorting Techniques – Data Structure and Algorithm Tutorials
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of elements in the respective data structure. Why Sorting Algorithms are ImportantThe sorting algorithm is important in Com
3 min read
Most Common Sorting Algorithms
Selection Sort
Selection Sort is a comparison-based sorting algorithm. It sorts an array by repeatedly selecting the smallest (or largest) element from the unsorted portion and swapping it with the first unsorted element. This process continues until the entire array is sorted. First we find the smallest element a
8 min read
Bubble Sort Algorithm
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high. We sort the array using multiple passes. After the fi
8 min read
Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that works by iteratively inserting each element of an unsorted list into its correct position in a sorted portion of the list. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. T
10 min read
Merge Sort - Data Structure and Algorithms Tutorials
Merge sort is a sorting algorithm that follows the divide-and-conquer approach. It works by recursively dividing the input array into smaller subarrays and sorting those subarrays then merging them back together to obtain the sorted array. In simple terms, we can say that the process of merge sort i
15 min read
Quick Sort
QuickSort is a sorting algorithm based on the Divide and Conquer that picks an element as a pivot and partitions the given array around the picked pivot by placing the pivot in its correct position in the sorted array. Table of Content How does QuickSort Algorithm work? Working of Partition Algorith
13 min read
Heap Sort - Data Structures and Algorithms Tutorials
Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
15 min read
Counting Sort - Data Structures and Algorithms Tutorials
What is Counting Sort?Counting Sort is a non-comparison-based sorting algorithm. It is particularly efficient when the range of input values is small compared to the number of elements to be sorted. The basic idea behind Counting Sort is to count the frequency of each distinct element in the input a
9 min read
Radix Sort - Data Structures and Algorithms Tutorials
Radix Sort is a linear sorting algorithm that sorts elements by processing them digit by digit. It is an efficient sorting algorithm for integers or strings with fixed-size keys. Rather than comparing elements directly, Radix Sort distributes the elements into buckets based on each digit's value. By
15+ min read
Bucket Sort - Data Structures and Algorithms Tutorials
Bucket sort is a sorting technique that involves dividing elements into various groups, or buckets. These buckets are formed by uniformly distributing the elements. Once the elements are divided into buckets, they can be sorted using any other sorting algorithm. Finally, the sorted elements are gath
8 min read
Other Sorting Algorithms
Shell Sort
Shell sort is mainly a variation of Insertion Sort. In insertion sort, we move elements only one position ahead. When an element has to be moved far ahead, many movements are involved. The idea of ShellSort is to allow the exchange of far items. In Shell sort, we make the array h-sorted for a large
8 min read
TimSort - Data Structures and Algorithms Tutorials
Tim Sort is a hybrid sorting algorithm derived from merge sort and insertion sort. It was designed to perform well on many kinds of real-world data. Tim Sort is the default sorting algorithm used by Python's sorted() and list.sort() functions. Tim Sort Algorithms The main idea behind Tim Sort is to
15+ min read
Comb Sort
Comb Sort is mainly an improvement over Bubble Sort. Bubble sort always compares adjacent values. So all inversions are removed one by one. Comb Sort improves on Bubble Sort by using a gap of the size of more than 1. The gap starts with a large value and shrinks by a factor of 1.3 in every iteration
8 min read
Pigeonhole Sort
Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same. It requires O(n + Range) time where n is number of elements in input array and 'Range' is number of possible values
7 min read
Cycle Sort
Cycle sort is an in-place, unstable sorting algorithm that is particularly useful when sorting arrays containing elements with a small range of values. It was developed by W. D. Jones and published in 1963. The basic idea behind cycle sort is to divide the input array into cycles, where each cycle c
15+ min read
Cocktail Sort
Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in the first iteration and second-largest in the second iteration and so on. Cocktail Sort traverses through a given array in both directio
15+ min read
Strand Sort
Strand sort is a recursive sorting algorithm that sorts items of a list into increasing order. It has O(n²) worst time complexity which occurs when the input list is reverse sorted. It has a best case time complexity of O(n) which occurs when the input is a list that is already sorted. Given a list
8 min read
Bitonic Sort
Background Bitonic Sort is a classic parallel algorithm for sorting. The number of comparisons done by Bitonic sort is more than popular sorting algorithms like Merge Sort [ does O(log N) comparisons], but Bitonic sort is better for parallel implementation because we always compare elements in a pr
13 min read
Pancake sorting
Given an unsorted array, the task is to sort the given array. You are allowed to do only following operation on array. flip(arr, i): Reverse array from 0 to i Examples: Input: arr[] = { 23, 10, 20, 11, 12, 6, 7 }Output: { 6, 7, 10, 11, 12, 20, 23} Input: arr[] = { 0, 1, 1, 0, 0 }Output: { 0, 0, 0, 1
15+ min read
BogoSort or Permutation Sort
BogoSort also known as permutation sort, stupid sort, slow sort, shotgun sort or monkey sort is a particularly ineffective algorithm one person can ever imagine. It is based on generate and test paradigm. The algorithm successively generates permutations of its input until it finds one that is sorte
7 min read
Gnome Sort
Gnome Sort also called Stupid sort is based on the concept of a Garden Gnome sorting his flower pots. A garden gnome sorts the flower pots by the following method- He looks at the flower pot next to him and the previous one; if they are in the right order he steps one pot forward, otherwise he swaps
5 min read
Sleep Sort – The King of Laziness / Sorting while Sleeping
In this algorithm we create different threads for each of the elements in the input array and then each thread sleeps for an amount of time which is proportional to the value of corresponding array element. Hence, the thread having the least amount of sleeping time wakes up first and the number gets
12 min read
Stooge Sort
Stooge Sort is a recursive sorting algorithm. It is not much efficient but interesting sorting algorithm. It generally divides the array into two overlapping parts (2/3 each). After that it performs sorting in first 2/3 part and then it performs sorting in last 2/3 part. And then, sorting is done on
6 min read
Tag Sort (To get both sorted and original)
This is not a new sorting algorithm, but an idea when we need to avoid swapping of large objects or need to access elements of a large array in both original and sorted orders. A common sorting task is to sort elements of an array using a sorting algorithm like Quick Sort, Bubble Sort.. etc, but the
10 min read
Tree Sort
Tree sort is a sorting algorithm that is based on Binary Search Tree data structure. It first creates a binary search tree from the elements of the input list or array and then performs an in-order traversal on the created binary search tree to get the elements in sorted order. Algorithm: Step 1: Ta
7 min read
Odd-Even Sort / Brick Sort
This is basically a variation of bubble-sort. This algorithm is divided into two phases- Odd and Even Phase. The algorithm runs until the array elements are sorted and in each iteration two phases occurs- Odd and Even Phases.In the odd phase, we perform a bubble sort on odd indexed elements and in t
5 min read
Comparison with other Sorting Algorithm
Selection Sort VS Bubble Sort
Not a valid contributionIn this, we will cover the comparison between Selection Sort VS Bubble Sort. The resources required by Selection Sort & Bubble Sort algorithms on the basis of Time and Space Complexity are as follows. Time Complexity - [Tex]O(n^2)[/Tex]Space Complexity - [Tex]O(1)[/Tex] L
13 min read
Difference between Insertion sort and Selection sort
Insertion sort and selection sort are two popular sorting algorithms, and their main difference lies in how they select and place elements in a sorted sequence. Selection Sort:In selection sort, the input array is divided into two parts: a sorted part and an unsorted part.The algorithm repeatedly fi
14 min read
Merge Sort vs. Insertion Sort
Pre-requisite: Merge Sort, Insertion Sort Merge Sort: is an external algorithm based on divide and conquer strategy. In this sorting: The elements are split into two sub-arrays (n/2) again and again until only one element is left.Merge sort uses additional storage for sorting the auxiliary array.M
14 min read
Radix Sort vs Bucket Sort
We have two standard sorting algorithms, named bucket sort and radix sort. They both share differences and similarities. Let’s explore some similarities, differences, advantages, and disadvantages here in more detail. Bucket Sort: Bucket sort is a sorting algorithm in which the elements are separate
6 min read
C qsort() vs C++ sort()
Standard C library provides qsort function that can be used for sorting an array. Following is the prototype of qsort() function. // Sort an array of any type. The parameters are, base // address of array, size of array and pointer to // comparator function void qsort (void* base, size_t num, size_t
4 min read
sort() vs. partial_sort() vs. nth_element() + sort() in C++ STL
In this article, we will discuss the difference between sort(), partial_sort(), and nth_element()+sort(). Below is the illustration of the above functions: sort(): C++ STL provides a function sort() that sorts a list of element in O(N*log N) time. By default, sort() sorts an array in ascending order
4 min read
Python - Difference between sorted() and sort()
Sorting means rearranging a given sequence of elements according to a comparison operator on the elements. The comparison operator is used to decide the new order of the elements in the respective data structure. For example, The below list of characters is sorted in increasing order of their ASCII
6 min read
Easy problems on Sorting algorihtms
Sort elements by frequency
Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first Examples: Input: arr[] = {2, 5, 2, 8, 5, 6, 8, 8}Output: arr[] = {8, 8, 8, 2, 2, 5, 5, 6} Input: arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}Output: arr[] = {8, 8, 8,
15+ min read
Sort an array of 0s, 1s and 2s - Dutch National Flag Problem
Given an array arr[] consisting of only 0s, 1s, and 2s. The task is to sort the array, i.e., put all 0s first, then all 1s and all 2s in last. This problem is the same as the famous "Dutch National Flag problem". The problem was proposed by Edsger Dijkstra. The problem is as follows: Given n balls o
13 min read
Sort numbers stored on different machines
Given N machines. Each machine contains some numbers in sorted form. But the amount of numbers, each machine has is not fixed. Output the numbers from all the machine in sorted non-decreasing form. Example: Machine M1 contains 3 numbers: {30, 40, 50}Machine M2 contains 2 numbers: {35, 45} Machine M3
15+ min read
Sort an array in wave form
Given an unsorted array of integers, sort the array into a wave array. An array arr[0..n-1] is sorted in wave form if:arr[0] >= arr[1] <= arr[2] >= arr[3] <= arr[4] >= ..... Input: arr[] = {10, 5, 6, 3, 2, 20, 100, 80}Output: arr[] = {10, 5, 6, 2, 20, 3, 100, 80} Explanation: here you
10 min read
Check if any two intervals intersect in a given set
An interval is represented as a combination of start time and end time. Given a set of intervals, check if any two intervals intersect. Examples: Input: arr[] = {{1, 3}, {5, 7}, {2, 4}, {6, 8}}Output: trueThe intervals {1, 3} and {2, 4} overlapInput: arr[] = {{1, 3}, {7, 9}, {4, 6}, {10, 13}}Output:
13 min read
How to sort an array of dates in C/C++?
Given an array of dates, how to sort them. Example: Input: Date arr[] = {{20, 1, 2014}, {25, 3, 2010}, { 3, 12, 1676}, {18, 11, 1982}, {19, 4, 2015}, { 9, 7, 2015}} Output: Date arr[] = {{ 3, 12, 1676}, {18, 11, 1982}, {25, 3, 2010}, {20, 1, 2014}, {19, 4, 2015}, { 9, 7, 2015}} We strongly recommend
3 min read
Sorting Strings using Bubble Sort
Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array. In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and are hence called sinking sort. At the end of each pa
4 min read
Sort an array according to count of set bits
Given an array of positive integers, sort the array in decreasing order of count of set bits in binary representations of array elements. For integers having the same number of set bits in their binary representation, sort according to their position in the original array i.e., a stable sort. For ex
15+ min read
Sort even-placed elements in increasing and odd-placed in decreasing order
We are given an array of n distinct numbers. The task is to sort all even-placed numbers in increasing and odd-placed numbers in decreasing order. The modified array should contain all sorted even-placed numbers followed by reverse sorted odd-placed numbers. Note that the first element is considered
15+ min read
Sort an array when two halves are sorted
Given an integer array of which both first half and second half are sorted. Task is to merge two sorted halves of array into single sorted array. Examples: Input : A[] = { 2, 3, 8, -1, 7, 10 } Output : -1, 2, 3, 7, 8, 10 Input : A[] = {-4, 6, 9, -1, 3 } Output : -4, -1, 3, 6, 9Recommended: Please so
10 min read
Sorting Big Integers
Given a array of n positive integers where each integer can have digits upto 106, print the array elements in ascending order. Input: arr[] = {54, 724523015759812365462, 870112101220845, 8723} Output: 54 8723 870112101220845 724523015759812365462Explanation:All elements of array are sorted in non-de
6 min read
Sort a linked list of 0s, 1s and 2s
Given a linked list of 0s, 1s and 2s, The task is to sort the list in non-decreasing order. Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULLOutput: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULLOutput: 0 -
15+ min read
Medium problems on Sorting algorithms
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read
Count Inversions of an Array
Given an integer array arr[] of size n, find the inversion count in the array. Two array elements arr[i] and arr[j] form an inversion if arr[i] > arr[j] and i < j. Note: Inversion Count for an array indicates that how far (or close) the array is from being sorted. If the array is already sorte
15+ min read
Find the Minimum length Unsorted Subarray, sorting which makes the complete array sorted
Given an unsorted array arr[0..n-1] of size n, find the minimum length subarray arr[s..e] such that sorting this subarray makes the whole array sorted. Examples: If the input array is [10, 12, 20, 30, 25, 40, 32, 31, 35, 50, 60], your program should be able to find that the subarray lies between ind
15+ min read
Sort a nearly sorted (or K sorted) array
Given an array and a number k where k is smaller than or equal to the size of the array. The given array is sorted in a way that every element is at-most k distance away from it sorted position. It means if we completely sort the array, then the index of the element can go from i - k to i + k where
10 min read
Sort n numbers in range from 0 to n^2 - 1 in linear time
Given an array of numbers of size n. It is also given that the array elements are in the range from 0 to n2 - 1. Sort the given array in linear time. Examples: Since there are 5 elements, the elements can be from 0 to 24.Input: arr[] = {0, 23, 14, 12, 9}Output: arr[] = {0, 9, 12, 14, 23}Since there
12 min read
Sort an array according to the order defined by another array
Given two arrays arr1[] and arr2[] of size m and n, the task is to sort arr1[] such that the relative order among the elements matches the order in arr2[]. For elements not present in arr2[], append them at the end in sorted order. Example: Input: arr1[] = {2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8} arr2[] =
14 min read
Find the point where maximum intervals overlap
Consider a big party where a log register for guest's entry and exit times is maintained. Find the time at which there are maximum guests in the party. Note that entries in register are not in any order.Example : Input: arrl[] = {1, 2, 9, 5, 5} exit[] = {4, 5, 12, 9, 12} First guest in array arrives
13 min read
Find a permutation that causes worst case of Merge Sort
Given a set of elements, find which permutation of these elements would result in worst case of Merge Sort.Asymptotically, merge sort always takes O(n Log n) time, but the cases that require more comparisons generally take more time in practice. We basically need to find a permutation of input eleme
12 min read
Sort Vector of Pairs in Ascending Order in C++
Sorting a vector of pairs in ascending order means arranging the elements in such a way that first pair is lesser than second pair, second pair is lesser than third pair and so on. The easiest way to sort the vector of pairs in ascending order is to use std::sort() function. The below code example i
4 min read
Minimum swaps to make two arrays consisting unique elements identical
Given two arrays that have the same values but in a different order and having no duplicate elements in it, we need to make a second array the same as a first array using the minimum number of swaps. Examples: Input : arrA[] = {3, 6, 4, 8}, arrB[] = {4, 6, 8, 3}Output : 2Explanation: we can make arr
12 min read
Chocolate Distribution Problem
Given an array arr[] of n integers where arr[i] represents the number of chocolates in ith packet. Each packet can have a variable number of chocolates. There are m students, the task is to distribute chocolate packets such that: Each student gets exactly one packet.The difference between the maximu
5 min read
Permute two arrays such that sum of every pair is greater or equal to K
Given two arrays of equal size n and an integer k. The task is to permute both arrays such that sum of their corresponding element is greater than or equal to k i.e a[i] + b[i] >= k. The task is to print "Yes" if any such permutation exists, otherwise print "No". Examples : Input : a[] = {2, 1, 3
7 min read
Bucket Sort To Sort an Array with Negative Numbers
We have discussed bucket sort in the main post on Bucket Sort . Bucket sort is mainly useful when input is uniformly distributed over a range. For example, consider the problem of sorting a large set of floating point numbers which are in range from 0.0 to 1.0 and are uniformly distributed across th
9 min read
Sort a Matrix in all way increasing order
Given a square matrix of order N*N having distinct elements, the task is to sort given matrix in such a way that its rows, columns and both diagonals (diagonal and anti-diagonal) are in increasing order. Examples: Input : arr[3][3] = {1, 4, 2, 3, 5, 6, 9, 7, 8} Output :{1, 2, 3, 4, 5, 6, 7, 8, 9} In
5 min read
Convert an Array to reduced form using Vector of pairs
Given an array with n distinct elements, convert the given array to a form where all elements are in range from 0 to n-1. The order of elements is same, i.e., 0 is placed in place of smallest element, 1 is placed for second smallest element, ... n-1 is placed for largest element. Input: arr[] = {10,
11 min read
Check if it is possible to sort an array with conditional swapping of adjacent allowed
We are given an unsorted array of integers in the range from 0 to n-1. We are allowed to swap adjacent elements in array many number of times but only if the absolute difference between these element is 1. Check if it is possible to sort the array.If yes then print "yes" else "no". Examples: Input :
5 min read
Hard problem on Sorting algorithms
Surpasser Count of Each Element in Array
Given an array of distinct integers arr[], the task is to find the surpasser count for each element of the array. A surpasser of an element in an array is any element to its right that is greater than it, i.e., arr[j] is a surpasser of arr[i] if i < j and arr[i] < arr[j]. The surpasser count o
15 min read
Partition into minimum subsets of consecutive numbers
Given an array of distinct positive numbers, the task is to partition the array into minimum number of subsets (or subsequences) such that each subset contains consecutive numbers only. Examples: Input: arr[] = [100, 56, 5, 6, 102, 58, 101, 57, 7, 103, 59]Output: 3Explanation: [5, 6, 7], [ 56, 57, 5
7 min read
Choose m elements having minimum difference between max and min
Given an array arr[] of n integers. The task is to pick exactly m elements such that the maximum difference between any pair of these m elements in minimum. Examples: Input: arr[] = {7, 3, 2, 4, 9, 12, 56}, m = 3 Output: 2 Explanation: We pick {3, 2, 4}, we will get the minimum difference, that is 2
5 min read
K-th smallest element after removing some integers from natural numbers
Given an array arr[] of size 'n' and a positive integer k. Consider series of natural numbers and remove arr[0], arr[1], arr[2], ..., arr[p] from it. Now the task is to find k-th smallest number in the remaining set of natural numbers. If no such number exists print "-1". Examples : Input : arr[] =
15+ min read
Maximum difference between frequency of two elements such that element having greater frequency is also greater
Given an array of n positive integers with many repeating elements. The task is to find the maximum difference between the frequency of any two different elements, such that the element with greater frequency is also greater in value than the second integer. Examples: Input : arr[] = { 3, 1, 3, 2, 3
12 min read
Minimum swaps to reach permuted array with at most 2 positions left swaps allowed
Given a permuted array of length N of first N natural numbers, we need to tell the minimum number of swaps required in the sorted array of first N natural number to reach given permuted array where a number can be swapped with at most 2 positions left to it. If it is not possible to reach permuted a
14 min read
Check if Array Elemnts can be Made Equal with Given Operations
Given an array arr[] consisting of N integers and following are the three operations that can be performed using any external number X. Add X to an array element once.Subtract X from an array element once.Perform no operation on the array element.Note : Only one operation can be performed on a numbe
6 min read
Sort an array after applying the given equation
We have an integer array that is sorted in ascending order. We also have 3 integers A, B and C. We need to apply A*x*x + B*x + C for each element x in the array and sort the modified array. Example: Input : arr[] = {-1, 0, 1, 2, 3, 4} A = -1, B = 2, C = -1Output : {-9, -4, -4, -1, -1, 0} Expalnation
13 min read
Print array of strings in sorted order without copying one string into another
Given an array of n strings. The task is to print the strings in sorted order. The approach should be such that no string should be copied to another string during the sorting process. Examples: Input : {"geeks", "for", "geeks", "quiz") Output : for geeks geeks quiz Input : {"ball", "pen", "apple",
7 min read