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
def sortByFreq ( arr , n ) : NEW_LINE INDENT maxE = - 1 ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT maxE = max ( maxE , arr [ i ] ) NEW_LINE DEDENT freq = [ 0 ] * ( maxE + 1 ) ; NEW_LINE for i in range ( n ) : NEW_LINE INDENT freq [ arr [ i ] ] += 1 ; NEW_LINE DEDENT cnt = 0 ; NEW_LINE for i in range ( maxE + 1 ) : NEW_LINE INDENT if ( freq [ i ] > 0 ) : NEW_LINE INDENT value = 100000 - i ; NEW_LINE arr [ cnt ] = 100000 * freq [ i ] + value ; NEW_LINE cnt += 1 ; NEW_LINE DEDENT DEDENT return cnt ; NEW_LINE DEDENT def printSortedArray ( arr , cnt ) : NEW_LINE INDENT for i in range ( cnt ) : NEW_LINE INDENT frequency = arr [ i ] / 100000 ; NEW_LINE value = 100000 - ( arr [ i ] % 100000 ) ; NEW_LINE for j in range ( int ( frequency ) ) : NEW_LINE INDENT print ( value , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 4 , 4 , 5 , 6 , 4 , 2 , 2 , 8 , 5 ] NEW_LINE n = len ( arr ) NEW_LINE cnt = sortByFreq ( arr , n ) ; NEW_LINE arr . sort ( reverse = True ) NEW_LINE printSortedArray ( arr , cnt ) ; NEW_LINE DEDENT