Sort ugly numbers in an array at their relative positions

Given an integer array arr[], the task is to sort only those elements which are ugly numbers at their relative positions in the array (positions of other elements must not be affected).
Ugly numbers are numbers whose only prime factors are 2, 3 or 5.
The sequence 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, ….. shows first few ugly numbers. By convention, 1 is included.

Examples:

Input: arr[] = {13, 9, 11, 3, 2}
Output: 13 2 11 3 9
9, 3 and 2 are the only ugly numbers in the given array.

Input: arr[] = {1, 2, 3, 7, 12, 10}
Output: 1 2 3 7 10 12

Approach:

  • Start traversing the array and for every element arr[i], if arr[i] is an ugly number then store it in an ArrayList and update arr[i] = -1
  • After all the ugly numbers have been stored in the ArrayList, sort the updated ArrayList.
  • Again traverse the array and for every element,
    • If arr[i] = -1 then print the first element from the ArrayList that hasn’t been printed before.
    • Else, print arr[i].

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// CPP implementation of the approach
#include<bits/stdc++.h>
using namespace std;
  
// Function that returns true if n is an ugly number
bool isUgly(int n)
{
    // While divisible by 2, keep dividing
    while (n % 2 == 0)
        n = n / 2;
  
    // While divisible by 3, keep dividing
    while (n % 3 == 0)
        n = n / 3;
  
    // While divisible by 5, keep dividing
    while (n % 5 == 0)
        n = n / 5;
  
    // n must be 1 if it was ugly
    if (n == 1)
        return true;
    return false;
}
  
// Function to sort ugly numbers
// in their relative positions
void sortUglyNumbers(int arr[], int n)
{
  
    // To store the ugly numbers from the array
    vector<int> list;
  
    int i;
    for (i = 0; i < n; i++)
    {
  
        // If current element is an ugly number
        if (isUgly(arr[i])) 
        {
  
            // Add it to the ArrayList
            // and set arr[i] to -1
            list.push_back(arr[i]);
            arr[i] = -1;
        }
    }
  
    // Sort the ugly numbers
    sort(list.begin(),list.end());
  
    int j = 0;
    for (i = 0; i < n; i++)
    {
  
        // Position of an ugly number
        if (arr[i] == -1)
            cout << list[j++] << " ";
        else
            cout << arr[i] << " ";
    }
}
  
// Driver code
int main()
{
    int arr[] = { 1, 2, 3, 7, 12, 10 };
    int n = sizeof(arr)/sizeof(arr[0]);
    sortUglyNumbers(arr, n);
}
  
// This code is contributed by
// Surendra_Gangwar

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
import java.util.ArrayList;
import java.util.Collections;
  
class GFG {
  
    // Function that returns true if n is an ugly number
    static boolean isUgly(int n)
    {
        // While divisible by 2, keep dividing
        while (n % 2 == 0)
            n = n / 2;
  
        // While divisible by 3, keep dividing
        while (n % 3 == 0)
            n = n / 3;
  
        // While divisible by 5, keep dividing
        while (n % 5 == 0)
            n = n / 5;
  
        // n must be 1 if it was ugly
        if (n == 1)
            return true;
        return false;
    }
  
    // Function to sort ugly numbers
    // in their relative positions
    static void sortUglyNumbers(int arr[], int n)
    {
  
        // To store the ugly numbers from the array
        ArrayList<Integer> list = new ArrayList<>();
  
        int i;
        for (i = 0; i < n; i++) {
  
            // If current element is an ugly number
            if (isUgly(arr[i])) {
  
                // Add it to the ArrayList
                // and set arr[i] to -1
                list.add(arr[i]);
                arr[i] = -1;
            }
        }
  
        // Sort the ugly numbers
        Collections.sort(list);
  
        int j = 0;
        for (i = 0; i < n; i++) {
  
            // Position of an ugly number
            if (arr[i] == -1)
                System.out.print(list.get(j++) + " ");
            else
                System.out.print(arr[i] + " ");
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        int arr[] = { 1, 2, 3, 7, 12, 10 };
        int n = arr.length;
        sortUglyNumbers(arr, n);
    }
}

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
using System.Collections.Generic;
      
class GFG 
{
  
    // Function that returns true 
    // if n is an ugly number
    static bool isUgly(int n)
    {
        // While divisible by 2, keep dividing
        while (n % 2 == 0)
            n = n / 2;
  
        // While divisible by 3, keep dividing
        while (n % 3 == 0)
            n = n / 3;
  
        // While divisible by 5, keep dividing
        while (n % 5 == 0)
            n = n / 5;
  
        // n must be 1 if it was ugly
        if (n == 1)
            return true;
        return false;
    }
  
    // Function to sort ugly numbers
    // in their relative positions
    static void sortUglyNumbers(int []arr, int n)
    {
  
        // To store the ugly numbers from the array
        List<int> list = new List<int>();
  
        int i;
        for (i = 0; i < n; i++)
        {
  
            // If current element is an ugly number
            if (isUgly(arr[i]))
            {
  
                // Add it to the ArrayList
                // and set arr[i] to -1
                list.Add(arr[i]);
                arr[i] = -1;
            }
        }
  
        // Sort the ugly numbers
        list.Sort();
  
        int j = 0;
        for (i = 0; i < n; i++)
        {
  
            // Position of an ugly number
            if (arr[i] == -1)
                Console.Write(list[j++] + " ");
            else
                Console.Write(arr[i] + " ");
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        int []arr = { 1, 2, 3, 7, 12, 10 };
        int n = arr.Length;
        sortUglyNumbers(arr, n);
    }
}
  
// This code contributed by Rajput-Ji

chevron_right


Output:

1 2 3 7 10 12


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.