Sorting element of an array by frequency in decreasing order | 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
function sortByFreq ( arr , n ) { var maxE = - 1 ; for ( var i = 0 ; i < n ; i ++ ) { maxE = Math . max ( maxE , arr [ i ] ) ; } var freq = new Array ( maxE + 1 ) . fill ( 0 ) ; for ( var i = 0 ; i < n ; i ++ ) { freq [ arr [ i ] ] ++ ; } var cnt = 0 ; for ( var i = 0 ; i <= maxE ; i ++ ) { if ( freq [ i ] > 0 ) { var value = 100000 - i ; arr [ cnt ] = 100000 * freq [ i ] + value ; cnt ++ ; } } return cnt ; } function printSortedArray ( arr , cnt ) { for ( var i = 0 ; i < cnt ; i ++ ) { var frequency = parseInt ( arr [ i ] / 100000 ) ; var value = 100000 - ( arr [ i ] % 100000 ) ; for ( var j = 0 ; j < frequency ; j ++ ) { document . write ( value + " " ) ; } } } var arr = [ 4 , 4 , 5 , 6 , 4 , 2 , 2 , 8 , 5 ] ; var n = arr . length ; var cnt = sortByFreq ( arr , n ) ; arr . sort ( ( a , b ) => b - a ) ; printSortedArray ( arr , cnt ) ;