![]() |
VOOZH | about |
Print the elements of an array in the decreasing frequency if 2 numbers have the same frequency then print the one which came first.
Examples:
Input : arr[] = {2, 5, 2, 8, 5, 6, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6}
Input : arr[] = {2, 5, 2, 6, -1, 9999999, 5, 8, 8, 8}
Output : arr[] = {8, 8, 8, 2, 2, 5, 5, 6, -1, 9999999}
We have discussed different approaches in below posts :
Sort elements by frequency | Set 1
Sort elements by frequency | Set 2
Sorting Array Elements By Frequency | Set 3 (Using STL)
All of the above approaches work in O(n Log n) time where n is total number of elements. In this post, a new approach is discussed that works in O(n + m Log m) time where n is total number of elements and m is total number of distinct elements.
The idea is to use hashing.
The below image is a dry run of the above approach:
We do not need to declare another map m2, as it does not provide the proper expected result for the problem.
instead, we need to just check for the first values of the pairs sent as parameters in the sortByVal function.
Below is the implementation of the above approach:
8 8 8 2 2 5 5 -1 6 9999999
Time Complexity: O(n) + O(m Log m) where n is total number of elements and m is total number of distinct elements
Auxiliary Space: O(n)
This article is contributed by Aarti_Rathi and Ankur Singh and improved by Ankur Goel.
Simple way to sort by frequency.
The Approach:
Here In This approach we first we store the element by there frequency in vector_pair format(Using Mapping stl map) then sort it according to frequency then reverse it and apply bubble sort to make the condition true decreasing frequency if 2 numbers have the same frequency then print the one which came first. then print the vector.
8 8 8 2 2 5 5 -1 6 9999999
Time Complexity: O(n^2) I.e it take O(n) for getting the frequency sorted vector but for sorting in decreasing frequency if 2 numbers have the same frequency then print the one which came first we use bubble sort so it take O(n^2).
Auxiliary Space: O(n),for vector.