Sort only non-prime numbers of an array in increasing order

Given an array of N integers. The task is to print the sorted array such that all numbers that are prime stay in the same place, sort only the non prime numbers.Â
Examples:Â
Input : arr[] = {10, 7, 6}
Output : 6 7 10
Input : arr[] = {100, 11, 500, 2, 17, 1}
Output : 1 11 100 2 17 500
Approach:Â
- Traverse the array, take out all non-prime numbers and store them in a vector.
- Now, sort the vector.
- Then, traverse the array again and check if a number is prime, if yes then print it as it is. Otherwise, print a number from the vector.
To check whether a number is prime or not we can use sieve-of-eratosthenes.
Below is the implementation of above approach:Â Â
C++
// C++ program to sort only non primes#include <bits/stdc++.h>using namespace std;Â
// Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.bool prime[100005];Â
void SieveOfEratosthenes(int n){Â
    memset(prime, true, sizeof(prime));Â
    prime[1] = false;Â
    for (int p = 2; p * p <= n; p++) {        // If prime[p] is not changed, then it is a prime        if (prime[p] == true) {            // Update all multiples of p            for (int i = p * 2; i <= n; i += p)                prime[i] = false;        }    }}Â
// Function to print the array such that// only non primes are sortedvoid sortedArray(int arr[], int n){Â Â Â Â SieveOfEratosthenes(100005);Â
    // vector v will store all non    // prime numbers    std::vector<int> v;Â
    // If not prime, insert into vector    for (int i = 0; i < n; ++i) {        if (prime[arr[i]] == 0)            v.push_back(arr[i]);    }Â
    // sorting vector of non primes    sort(v.begin(), v.end());Â
    int j = 0;    // print the required array    for (int i = 0; i < n; ++i) {        if (prime[arr[i]] == true)            cout << arr[i] << " ";        else {            cout << v[j] << " ";            j++;        }    }}Â
// Driver Codeint main(){Â
    int n = 6;    int arr[] = { 100, 11, 500, 2, 17, 1 };Â
    sortedArray(arr, n);Â
    return 0;} |
Java
   // Java program to sort only non primesimport java.util.*;class solution{// Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.static boolean prime[] = new boolean[100006];Â
static void SieveOfEratosthenes(int n){Â
    for(int i=1;i<=n;i++)    prime[i]=true;    prime[1] = false;Â
    for (int p = 2; p * p <= n; p++) {        // If prime[p] is not changed, then it is a prime        if (prime[p] == true) {            // Update all multiples of p            for (int i = p * 2; i <= n; i += p)                prime[i] = false;        }    }}Â
// Function to print the array such that// only non primes are sortedstatic void sortedArray(int arr[], int n){Â Â Â Â SieveOfEratosthenes(100005);Â
    // vector v will store all non    // prime numbers    Vector<Integer> v = new Vector<Integer>();Â
    // If not prime, insert into vector    for (int i = 0; i < n; ++i) {        if (prime[arr[i]]==false)            v.add(arr[i]);    }Â
    // sorting vector of non primes    Collections.sort(v);Â
    int j = 0;    // print the required array    for (int i = 0; i < n; ++i) {        if (prime[arr[i]] == true)            System.out.print( arr[i] + " ");        else {            System.out.print( v.get(j) + " ");            j++;        }    }}Â
// Driver Codepublic static void main(String args[]){Â
    int n = 6;    int arr[] = { 100, 11, 500, 2, 17, 1 };Â
    sortedArray(arr, n);Â
}}//contributed by Arnab Kundu |
Python3
# Python3 program to sort only # non primesÂ
# from math import sqrt methodfrom math import sqrtÂ
# Create a boolean array "prime[0..n]" # and initialize all entries it as true.# A value in prime[i] will finally be false # if i is Not a prime, else true. prime = [0] * 100005Â
def SieveOfEratosthenes(n) :Â
    for i in range(len(prime)) :        prime[i] = True             prime[1] = FalseÂ
    for p in range(2, int(sqrt(n)) + 1) :                 # If prime[p] is not changed,         # then it is a prime            if prime[p] == True :Â
            # Update all multiples of p             for i in range(p * 2, n, p) :                prime[i] = FalseÂ
Â
# Function to print the array such that # only non primes are sorted def sortedArray(arr, n) :Â Â Â Â Â Â Â Â Â SieveOfEratosthenes(100005)Â
    # list v will store all non     # prime numbers     v = []Â
    # If not prime, insert into list    for i in range(n) :        if prime[arr[i]] == 0 :            v.append(arr[i])Â
    # sorting list of non primes     v.sort()Â
    j = 0Â
    # print the required array    for i in range(n) :Â
        if prime[arr[i]] == True :            print(arr[i],end = " ")        else :            print(v[j],end = " ")            j += 1             Â
# Driver codeif __name__ == "__main__" :Â
    n = 6    arr = [100, 11, 500, 2, 17, 1]         sortedArray(arr, n)     # This code is contributed by # ANKITRAI1 |
C#
// C# program to sort only non primesusing System;using System.Collections.Generic;Â
class GFG{    // Create a boolean array "prime[0..n]"     // and initialize all entries it as true.    // A value in prime[i] will finally be    // false if i is Not a prime, else true.    static bool []prime = new bool[100006];Â
    static void SieveOfEratosthenes(int n)    {Â
        for(int i = 1; i <= n; i++)        prime[i] = true;        prime[1] = false;Â
        for (int p = 2; p * p <= n; p++)         {            // If prime[p] is not changed, then it is a prime            if (prime[p] == true)            {                // Update all multiples of p                for (int i = p * 2; i <= n; i += p)                    prime[i] = false;            }        }    }Â
    // Function to print the array such that    // only non primes are sorted    static void sortedArray(int []arr, int n)    {        SieveOfEratosthenes(100005);Â
        // vector v will store all non        // prime numbers        List<int> v = new List<int>();Â
        // If not prime, insert into vector        for (int i = 0; i < n; ++i)        {            if (prime[arr[i]] == false)                v.Add(arr[i]);        }Â
        // sorting vector of non primes        v.Sort();Â
        int j = 0;        // print the required array        for (int i = 0; i < n; ++i)         {            if (prime[arr[i]] == true)                Console.Write( arr[i] + " ");            else            {                Console.Write( v[j] + " ");                j++;            }        }    }Â
    // Driver Code    public static void Main()    {Â
        int n = 6;        int []arr = { 100, 11, 500, 2, 17, 1 };Â
        sortedArray(arr, n);    }}Â
/* This code contributed by PrinciRaj1992 */ |
Javascript
<script>Â
// JavaScript program to sort only non primesÂ
// Create a boolean array "prime[0..n]" and initialize// all entries it as true. A value in prime[i] will// finally be false if i is Not a prime, else true.prime = new Array(100005);Â
function SieveOfEratosthenes( n){Â
    prime.fill(true);Â
    prime[1] = false;Â
    for (var p = 2; p * p <= n; p++) {        // If prime[p] is not changed, then it is a prime        if (prime[p] == true) {            // Update all multiples of p            for (var i = p * 2; i <= n; i += p)                prime[i] = false;        }    }}Â
// Function to print the array such that// only non primes are sortedfunction sortedArray(arr, n){Â Â Â Â SieveOfEratosthenes(100005);Â
    // vector v will store all non    // prime numbers    var v = [];Â
    // If not prime, insert into vector    for (var i = 0; i < n; ++i) {        if (prime[arr[i]] == 0)            v.push(arr[i]);    }Â
    // sorting vector of non primes    v.sort();Â
    var j = 0;    // print the required array    for (var i = 0; i < n; ++i) {        if (prime[arr[i]] == true)            document.write( arr[i] + " ");        else {            document.write( v[j] + " ");            j++;        }    }}var n = 6;var arr = [ 100, 11, 500, 2, 17, 1 ];sortedArray(arr, n);Â
// This code is contributed by SoumikMondalÂ
</script> |
Output
1 11 100 2 17 500
Time Complexity:Â
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



