Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to arrange an array in decreasing order of frequency of each number?

Input : {5, 13, 6, 5, 13, 7, 8, 6, 5}

Output : {5, 5, 5, 13, 13, 6, 6, 7, 8}

The question is to arrange the numbers in the array in decreasing order of their frequency, preserving the order of their occurrence.

If there is a tie, like in this example between 13 and 6, then the number occurring first in the input array would come first in the output array.

like image 911
Rajendra Uppal Avatar asked Mar 25 '10 16:03

Rajendra Uppal


People also ask

How do you sort an array into descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.


1 Answers

I guess I'd do it like this:

Use a key-value data structure where the number itself is the key and the occurrence count and first occurrence index are the value.

Now traverse all numbers. If the number is not yet known (in the data structure), add it, remembering the current index as well as 1 as count. Otherwise, increment the count.

Now sort the data structure contents by the occurrence count (decreasing) and the occurrence index (increasing), and output the result (repeating the number using the occurrence count).

Processing space used <= N, time used depending on data structure and dictionary would probably be about O(N log N)

like image 85
Lucero Avatar answered Sep 24 '22 03:09

Lucero