Sort the array elements based on the elements frequency in java

sort array elements by frequency in descending order in java
sort the array according to frequency of elements in c
sort elements by frequency in python
sort array based on frequency javascript
order digits based on frequency in c
frequency sort array amcat in c
print numbers frequency based in java
java arraylist sort by frequency

I have written a code to sort the array in java based on the frequency of the elements in it. I need a better code or pseudo code (with out collection framework).Please help with links or code.

public class SortByFreq1 {

    public static void main(String[] args) {

        int arr[] = { 2, 5, 2, 8, 5, 6, 8, 8, 0, -8 };

        int nArr[] = new int[arr.length];

        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        Map<Integer,Integer> sortmap = new HashMap<Integer, Integer>();
        ArrayList<Integer> arrList = new ArrayList<Integer>();

        for (int i = 0; i < arr.length; i++) {
            arrList.add(arr[i]);
        }

        Set<Integer> set = new HashSet<Integer>(arrList);

        for (Integer i : set) {  
            map.put(i, Collections.frequency(arrList, i));   
        }

        // System.out.println(map.keySet());
        // sort map by value

        Set<Entry<Integer,Integer>> valList=map.entrySet();
        ArrayList<Entry<Integer, Integer>> tempLst = new ArrayList<Map.Entry<Integer, Integer>>(valList);

        Collections.sort(tempLst, new Comparator<Entry<Integer, Integer>>() {
            @Override
            public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        int k = 0;

        for (Entry<Integer, Integer> entry : tempLst) {
            int no = entry.getKey();
            int noOfTimes = entry.getValue();

            int i = 0;

            while (i < noOfTimes) {
                nArr[k++] = no;
               i++;
            }
        }

        for (int i = 0; i < nArr.length; i++)
            System.out.print(nArr[i] + " ");
    }
} 

I'm just curious why couldn't you use the good old bubble sort in the case and just customize a bit the Bubble In worst case scenario the time complexity is going to be O(n*n) and space complexity will be O(3n) :)

Pure arrays implementation is going to be something like:

private static void bubbleSortByOccurrences(int[] arr) {
    int[][] counter = new int[2][arr.length];
    int counterIndex = -1;

    for (int value : arr) {
        int idx = 0;
        for (; idx <= counterIndex; idx++) {
            if (counter[0][idx] == value) {
                counter[1][idx]++;

                while (idx > 0 && counter[1][idx] > counter[1][idx-1]) {
                    int temp = counter[1][idx];
                    counter[0][idx] = counter[0][idx-1];
                    counter[1][idx] = counter[1][idx-1];
                    counter[0][idx-1] = value;
                    counter[1][idx-1] = temp;
                    idx--;
                }
                break;
            }
        }

        if (idx > counterIndex) {
            counter[0][idx] = value;
            counter[1][idx]++;
            counterIndex = idx;
        }
    }

    fillArrayBackwards(arr, counter, counterIndex);
}

private static void fillArrayBackwards(int[] buf, int[][] counter, int counterIndex) {
    for (int i = counterIndex, j = buf.length - 1; i >=0; i--) {
        for (int k = 0; k < counter[1][i]; k++) {
            buf[j--] = counter[0][i];
        }
    }
}

And the same algorithm implemented by using a Bubble class will look something like:

private static void bubbleSortByOccurrences(int[] arr) {
    Bubble head = null;

    for (int value : arr) {
        if (head == null) {
            head = new Bubble(value);
        } else {
            Bubble currentHead = null;
            Bubble current = head;

            for (; current != null && !(current.getValue() == value); current = current.getTail()) {
                currentHead = current;
            }

            if (current == null) {
                current = new Bubble(value);
                current.setTail(head);
                head = current;
            } else {
                current.incrementOccurrences();

                while (current.getTail() != null && current.getOccurrences() > current.getTail().getOccurrences()) {
                    Bubble currentTail = current.getTail();
                    current.setTail(currentTail.getTail());
                    currentTail.setTail(current);

                    if (currentHead != null) {
                        currentHead.setTail(currentTail);
                        currentHead = currentTail;
                    } else {
                        head = currentTail;
                    }
                }
            }
        }
    }

    fillArrayBackwards(arr, head);
}

private static void fillArrayBackwards(int[] buf, Bubble head) {
    int i = buf.length - 1;
    for (Bubble current = head; current != null; current = current.getTail()) {
        for (int j = 0; j < current.getOccurrences(); j++) {
            buf[i--] = current.getValue();
        }
    }
}

Where the custom defined bubble is as follows:

class Bubble {
    private int value;
    private int occurrences;
    private Bubble tail;

    public Bubble(int value) {
        this.value = value;
        this.occurrences = 1;
    }

    public int getValue() {
        return value;
    }

    public int getOccurrences() {
        return occurrences;
    }

    public void incrementOccurrences() {
        this.occurrences++;
    }

    public Bubble getTail() {
        return tail;
    }

    public void setTail(Bubble tail) {
        this.tail = tail;
    }
}

Sort elements by frequency, Use a sorting algorithm to sort the elements O(nlogn); Scan the sorted array and construct a 2D array of element and count O(n). Sort the 2D array according to  Sort elements by frequency | Set 1. Print the elements of an array in the decreasing frequency if 2 numbers have same frequency then print the one which came first. Examples: Scan the sorted array and construct a 2D array of element and count O(n). Sort the 2D array according to count O(nlogn).

Sort elements by frequency, I'm just curious why couldn't you use the good old bubble sort in the case and just customize a bit the Bubble In worst case scenario the time  Given an array, Sort the array according to the frequency of the elements Example. INPUT: arr[] = {1,1,3,3,3,6,6,6,6} OUTPUT: {6,6,6,6,3,3,3,1,1} Time Complexity: O(nlogn) In this method the main idea is to insert the elements in BST one by one and if the element is already present then increment the count of the node.

Can be done in O(n) using pigeonhole sort. Pseudo code:

counts = new HashMap<Item, int>(),;
foreach item in elements:
     counts[item] += 1;
buckets = new List<Item>[elements.length+1];
foreach item in counts:
    buckets[counts[item]].Append(item)

for i from 1 to elements.length:
   bucket = buckets[i]; /* edit: looping over i instead over bucket */
   for item in bucket:
      /* edit: if the out has to preserve the original number of elements
               such as [1,5,5,0,1,9,1] will print
               9,0,5,5,1,1,1 instead of 9,0,5,1, then the next line
               has to be repeated i times*/
      System.out.println(item)

edit: The same can be written without collection framework, by implementing a hash table and a linked list:

class Node {
   public Node next;
   public int value;
};
log2count = Math.ceil(Math.log(elements.length) / Math.log(2));
hashSize = (int) Math.Round(Math.Pow(2, log2count) * 2);

/* countsQuadraticProbing[i] is 0 if the hash entry is empty,
   otherwise it contains the frequency of the element in
   elementsQuadraticProbing[i].
   Note that quadratic probing over a hash table of size 2**k,
   and probing of  (0.5 i + 0.5 i**2) is guaranteed to find an empty
   entry if the hash table is not full.
*/
countsQuadraticProbing = new int[hashSize];
elementsQuadraticProbing = new int[hashSize];
foreach item in elements:
     for i from 0 to hashSize-1:
        index = (item + (i * (i + 1) / 2)) % hashSize;
        if countsQuadraticProbing[index] == 0:
           countsQuadraticProbing[index] = 1;
           elementsQuadraticProbing[index] = item;
           break;
        if elementsQuadraticProbing[index] == item:
           countsQuadraticProbing[index]++;
           break;

buckets = new Node[elements.length+1];
for i from 0 to hashSize-1:
    count = countsQuadraticProbing[index];
    if count != 0:
       Node topNode = new Node();
       topNode.next = buckets[count];
       topNode.value = elementsQuadraticProbing[i];
       buckets[count] = topNode;

/* there are O(N) buckets, total of elements in all buckets O(N),
   overall complexity of the nested loop O(N)
*/
for i from 1 to elements.length:
   node = buckets[i]  /* edit: using i for iteration */
   while node != null:
      /* edit: if the out has to preserve the original number of elements
               such as [1,5,5,0,1,9,1] will print
               9,0,5,5,1,1,1 instead of 9,0,5,1, then the next line
               has to be repeated i times*/
      System.out.println(node.value);
      node = node.next;

Sort the array elements based on the elements frequency in java , Given an array, sort its element by their frequency and index. i.e. Custom sort by element's frequency and index sort the vector based on custom comparator Please use our online compiler to post code in comments using C, C++, Java,  Sort array elements by frequency in descending order - Core Java Questions - Arrays and Loops In Java : Arrays are very useful in reducing the number of variables created and in reducing the code complexity.

your solution is better but since am not using any collections it is gonna be huge.

1.sort the list 2. get the frequency of every element 3. create a new arraylist/ array and store the elements that have higher frequency to lower frequency.

  1. sort the list using any sort algorithm
  2. get the frequency

      class CountFrequencies 
    {
     // Function to find counts of all elements present in
     // arr[0..n-1]. The array elements must be range from
     // 1 to n
     void findCounts(int arr[], int n) 
     {
    // Traverse all array elements
    int i = 0;
    while (i < n) 
    {
        // If this element is already processed,
        // then nothing to do
        if (arr[i] <= 0) 
        {
            i++;
            continue;
        }
    
        // Find index corresponding to this element
        // For example, index for 5 is 4
        int elementIndex = arr[i] - 1;
    
        // If the elementIndex has an element that is not
        // processed yet, then first store that element
        // to arr[i] so that we don't loose anything.
        if (arr[elementIndex] > 0) 
        {
            arr[i] = arr[elementIndex];
    
            // After storing arr[elementIndex], change it
            // to store initial count of 'arr[i]'
            arr[elementIndex] = -1;
        } 
        else
        {
            // If this is NOT first occurrence of arr[i],
            // then increment its count.
            arr[elementIndex]--;
    
            // And initialize arr[i] as 0 means the element
            // 'i+1' is not seen so far
            arr[i] = 0;
            i++;
        }
    }
    
    System.out.println("Below are counts of all elements");
    for (int j = 0; j < n; j++)
        System.out.println(j+1 + "->" + Math.abs(arr[j]));
     }
    

above code should give you an output:

1 -> 3
2 -> 0
3 -> 2
4 -> 0
5 -> 2
6 -> 0
7 -> 2
8 -> 0
9 -> 2
10 -> 0
11 -> 0
  1. Now you can easily use the array that stored the frequency of every element to create a new array that contains the most frequent elements in the array Note that the list is sorted so that arr[0] is the frequency of 1 arr[1] is the frequency of 2 and so on. Again The code is not efficient as yours it is better to use the collection framework. or if you are familiar use binary trees you can add the element into the tree and use inorder traversal ! Hope you find my answer helpful

Custom Sort, Write a program to sort given array according to frequency of occurrence of numbers, in descending order. Input (int[]), Output (int[]). {1, 4, 3, 4, 5, 4, 5}  Sort elements by frequency | Set 5 (using Java Map) Maximum difference between frequency of two elements such that element having greater frequency is also greater; Sort a string according to the frequency of characters; Sort an array of Strings according frequency; Minimum increment or decrement required to sort the array | Top-down Approach; Sort an array of strings based on the frequency of good words in them

Sort array elements by frequency in descending order, 2) Scan the sorted array and construct a 2D array of element and count O(n). 3) Sort the 2D array according to count O(nlogn). Input 2,3,4,2,8,1,1  Method 1 (Use Sorting) 1) Use quick sort algorithm to sort the elements O(nlogn) 2) Scan the sorted array and construct a 2D array of element and count O(n). 3) Sort the 2D array according to count O(nlogn).

Sorting of Array Depending on Frequency of Elements, Sort the elements of an array by number of times they repeated in ascending order. For Example Step 2: You got the frequency for each element in the array, now apply sorting logic based on the frequency. import java.util. Given an array, sort its element by their frequency and index. i.e. – If two elements have the different frequencies, then the one which has more frequency should come first. – If two elements have the same frequencies, then the one which has less index should come first.

Sort Elements By Frequency, Sort elements by frequency, print the elements of an array in the decreasing I feel like it might be slower that using extra structure and built-in sorting, but anyway: package bloomberg; import java.util.ArrayList; import java.util.​Collections; Sort by Frequency - Sort array elements in such a way that the element with the highest number of occurences comes first. If the number of occurences are equal then the print the number which appeared first in the array.

Comments
  • Any reason for (with out collection framework)?
  • Interviewer asked me not to use and also cost of my logic seems to be more.
  • ok. You can put all distinct elements in a map and then create a binary search tree out of it. Then, do an inorder traversal and you are done
  • Can you define what could be considered better?
  • By "with out collection framework" you mean without Set Map List etc. types or without Collections utility class?
  • The question asks for a solution that doesn't use the collections framework. Map is in the collections framework.
  • @Sammetanagasrinivas I was kind of confused. But will enclose one to handle that case. By the way, the numbers inside of the array have some ranges? This question can be optimized in several ways, it takes time to implement them all. I will try to add them after my on-hand work.
  • @Hearen Like you said, integer ranges plays a very big role here. I presume we will have to settle for a less efficient solution if ranges are completely off. Like [1,2147483647,1]
  • @vivek_23 updated with the solution solving that situation and also a comparison made for support.
  • java.util.Arrays is "a member of the Java Collections Framework."
  • one: collection is not allowed as OP required; two: bucket sort is not the ideal choice here - counting is better.
  • Counting sort won't work here, since counting sort works on sets of integers, and here there is a map of key value pairs. Regarding containers, I find a hash table trivial to implement, and implementing it here would have obfuscated the answer.
  • We can make hash array for the counting while bucket sort is recursively sorting the bucket and OP's question is about frequency from the beginning as you must have known.
  • The OP wants to sort the original elements based on their frequency: "sort the array in java based on the frequency of the elements in it". So the question is about the elements and their order, which happens to be based of frequency.
  • You are right wrt Wikipedia's bucket sort, which surprises me. In the early 90's, when I learned bucket sort it was a different thing. I'll update the description when I find the algorithm I have known as bucket sort.