Custom Sort | Sort elements by their frequency and Index

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.


 

For example,


Input:   [3, 3, 1, 1, 1, 8, 3, 6, 8, 7, 8]
Output: [3, 3, 3, 1, 1, 1, 8, 8, 8, 6, 7]

 


 

The idea is to write a custom compare method to solve this problem. Let the two element to be compared are x and y. Then

1. If x and y have the different frequencies, then the one which has more frequency should be treated as smaller than the other.

2. If x and y have the same frequencies, then the one which has less index should be treated as smaller than the other.

C++

Download   Run Code

Java

Download   Run Code

Output:

3 3 3 1 1 1 8 8 8 6 7

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of