Sorting of elements by frequency in Java

Sorting of elements by frequency in Java

Here, in this page we will discuss the program for sorting of elements by frequency frequency in Java programming language. We are given with an integer array and need to sort the array on the basis of there occurence.
Sorting element in array by frequency using C++

Sort Elements by Frequency of Occurrences in Java

To solve sort elements by frequency of occurrences in Java, we can use an array to count the occurrences of each element , and then use a sorting algorithm to sort the elements by their counts . Lets see this in detail .

Sort-elements-by-frequency-of-occurrences-code-in-Java

Method Discussed :

  • Method 1 : Naive Approach
  • Method 2 : Using Hash-map and then sorting.
Let’s discuss both methods one by one in brief.

Method 1 :

  • First we declare an array.
  • Declare two 2d array arr[MAX][2] and brr[MAX][2].
  • Store 1d array in 0th index of arr array.
  • Set arr[][1] = 0for all indexes upto n.
  • Now, count the frequency of elements of the array.
  • If element is unique the push it at brr[][0] array, and its frequency will represent by brr[][1].
  • Now, sort the brr on the basis of frequency.
  • Print the brr array on basis of their frequency.

Method 1 :

Run
import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] a = {10, 20, 10, 10, 20, 30, 30, 30, 30, 0};
        int n = a.length;
        int[][] arr = new int[256][2];
        int[][] brr = new int[256][2];
        int k = 0, temp, count;

        for (int i = 0; i < n; i++) {
            arr[i][0] = a[i];
            arr[i][1] = 0;
        }

        // Unique elements and its frequency are stored in another array
        for (int i = 0; i < n; i++) {
            if (arr[i][1] != 0) {
                continue;
            }
            count = 1;
            for (int j = i + 1; j < n; j++) {
                if (arr[i][0] == arr[j][0]) {
                    arr[j][1] = 1;
                    count++;
                }
            }
            brr[k][0] = arr[i][0];
            brr[k][1] = count;
            k++;
        }
        n = k;

        // Store the array and its frequency in sorted form
        for (int i = 0; i < n - 1; i++) {
            temp = brr[i][1];
            for (int j = i + 1; j < n; j++) {
                if (temp < brr[j][1]) {
                    temp = brr[j][1];
                    brr[j][1] = brr[i][1];
                    brr[i][1] = temp;

                    temp = brr[j][0];
                    brr[j][0] = brr[i][0];
                    brr[i][0] = temp;
                }
            }
        }

        System.out.println("Sorted Array based on its frequency:");
        for (int i = 0; i < n; i++) {
            while (brr[i][1] != 0) {
                System.out.print(brr[i][0] + " ");
                brr[i][1]--;
            }
        }
    }
}

Output

30 30 30 30 10 10 10 20 20 0

Method 2 :

In this method we will use the concept of hashing. We first declare the hash map and insert all the elements in the map, in which key represents the array elements and value represents the count of their occurrence.

Method 2 :

Run
import java.util.*;

public class Main {
    // Compare function
    static int compare(Map.Entry< Integer, Map.Entry< Integer, Integer>> p, Map.Entry< Integer, Map.Entry< Integer, Integer>> p1) {
        if (p.getValue().getValue() != p1.getValue().getValue())
            return Integer.compare(p1.getValue().getValue(), p.getValue().getValue());
        else
            return Integer.compare(p.getValue().getKey(), p1.getValue().getKey());
    }
    static void sortByFrequency(int[] arr, int n) {
        Map< Integer, Map.Entry< Integer, Integer>> mp = new HashMap<>();
        for (int i = 0; i < n; i++) {
            if (mp.containsKey(arr[i]))
                mp.get(arr[i]).setValue(mp.get(arr[i]).getValue() + 1);
            else
                mp.put(arr[i], new AbstractMap.SimpleEntry< Integer, Integer>(i, 1));
        }
        List< Map.Entry< Integer, Map.Entry< Integer, Integer>>> b = new ArrayList<>(mp.entrySet());
        Collections.sort(b, (p, p1) -> compare(p, p1));

        for (Map.Entry< Integer, Map.Entry< Integer, Integer>> it : b) {
            int count = it.getValue().getValue();
            while (count-- > 0)
                System.out.print(it.getKey() + " ");
        }
    }

    // Driver Function
    public static void main(String[] args) {
        int[] arr = {10, 20, 10, 10, 20, 30, 30, 30, 30, 0};
        int n = arr.length;

        sortByFrequency(arr, n);
    }
}

Output

30 30 30 30 10 10 10 20 20 0

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Arrays

  • Introduction to Arrays – CC++ | Java
  • Introduction to 2-D Arrays – CC++ Java
  • Sorting of Array – C | C++ | Java
  • Array Rotation – CC++ | Java
  • Reverse an array or string- CC++ | Java
  • Find pairs in array with given sum – CC++ | Java
  • Sort the array in Waveform – CC++ | Java
  • Majority Element in Array – CC++ | Java
  • Boyer-Moore’s Voting Algorithm – CC++ | Java
  • K-pairs with smallest sum in 2 arrays – C | C++ | Java
  • Largest Sum Contigous SubArray – CC++ | Java
  • Maximum Average Sub-array of K length – CC++ | Java
  • Size of sub-array with max sum – CC++ | Java
  • Sub-array with given sum – CC++ | Java
  • Triplet that sum to a given value – CC++ | Java
  • Segregate 0’s and 1’s in array – CC++ | Java
  • Segregate 0’s 1’s and 2’s in array – CC++ | Java
  • Sort elements in array by frequency – CC++ | Java
  • Finding pythagorean triplets in an array – CC++ | Java
  • Reorder array using given indexes – CC++ | Java
  • Merging two sorted arrays – CC++ | Java
  • Minimum number of Merge Operations to make an Array Palindrome – CC++ | Java
  • Find Zeros to be Flipped so that number of Consecutive 1’s is maximized – CC++ | Java