Sort ugly numbers in an array at their relative positions | Function that returns true if n is an ugly number ; While divisible by 2 , keep dividing ; While divisible by 3 , keep dividing ; While divisible by 5 , keep dividing ; n must be 1 if it was ugly ; Function to sort ugly numbers in their relative positions ; To store the ugly numbers from the array ; If current element is an ugly number ; Add it to the ArrayList and set arr [ i ] to - 1 ; Sort the ugly numbers ; Position of an ugly number ; Driver code
def isUgly ( n ) : NEW_LINE INDENT while n % 2 == 0 : NEW_LINE INDENT n = n // 2 NEW_LINE DEDENT while n % 3 == 0 : NEW_LINE INDENT n = n // 3 NEW_LINE DEDENT while n % 5 == 0 : NEW_LINE INDENT n = n // 5 NEW_LINE DEDENT if n == 1 : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def sortUglyNumbers ( arr , n ) : NEW_LINE INDENT list = [ ] NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if isUgly ( arr [ i ] ) : NEW_LINE INDENT list . append ( arr [ i ] ) NEW_LINE arr [ i ] = - 1 NEW_LINE DEDENT DEDENT list . sort ( ) NEW_LINE j = 0 NEW_LINE for i in range ( 0 , n ) : NEW_LINE INDENT if arr [ i ] == - 1 : NEW_LINE INDENT print ( list [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT else : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 1 , 2 , 3 , 7 , 12 , 10 ] NEW_LINE n = len ( arr ) NEW_LINE sortUglyNumbers ( arr , n ) NEW_LINE DEDENT