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:

arr[] = [3, 3, 1, 1, 1, 8, 3, 6, 8, 7, 8]

Output:

arr[] = [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

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz