text: Sorting element of an array by frequency in decreasing order | Java program to sort an array in decreasing order of their frequency ; Function that return the index upto all the array elements are updated . ; Initialise maxE = - 1 ; Find the maximum element of arr [ ] ; Create frequency array freq [ ] ; Update the frequency array as per the occurrence of element in arr [ ] ; Initialise cnt to 0 ; Traversing freq [ ] ; If freq of an element is greater than 0 update the value of arr [ ] at index cnt & increment cnt ; Return cnt ; Function that print array arr [ ] elements in sorted order ; Traversing arr [ ] till index cnt ; Find frequency of elements ; Find value at index i ; Traversing till frequency to print value at index i ; Driver code ; Size of array arr [ ] ; Function call to get cnt ; Sort the arr [ ] in decreasing order ; Function that prints elements in decreasing order
code: import java . util . * ; class GFG { static int sortByFreq ( Integer [ ] arr , int n ) { int maxE = - 1 ; for ( int i = 0 ; i < n ; i ++ ) { maxE = Math . max ( maxE , arr [ i ] ) ; } int freq [ ] = new int [ maxE + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } int cnt = 0 ; for ( int i = 0 ; i <= maxE ; i ++ ) { if ( freq [ i ] > 0 ) { int value = 100000 - i ; arr [ cnt ] = 100000 * freq [ i ] + value ; cnt ++ ; } } return cnt ; } static void printSortedArray ( Integer [ ] arr , int cnt ) { for ( int i = 0 ; i < cnt ; i ++ ) { int frequency = arr [ i ] / 100000 ; int value = 100000 - ( arr [ i ] % 100000 ) ; for ( int j = 0 ; j < frequency ; j ++ ) { System . out . print ( value + " ▁ " ) ; } } } public static void main ( String [ ] args ) { Integer arr [ ] = { 4 , 4 , 5 , 6 , 4 , 2 , 2 , 8 , 5 } ; int n = arr . length ; int cnt = sortByFreq ( arr , n ) ; Arrays . sort ( arr , Collections . reverseOrder ( ) ) ; printSortedArray ( arr , cnt ) ; } }