Open In App

Segregate Prime and Non-Prime Numbers in an array

Last Updated : 06 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array arr[] of size N, the task is to rearrange the array elements such that all the Prime numbers are placed before the Non-prime numbers.

Examples:

Input: arr[] = {1, 8, 2, 3, 4, 5, 7, 20}
Output: 7 5 2 3 4 8 1 20
Explanation:
The output consists of all the prime numbers 7 5 2 3, followed by Non-Prime numbers 4 8 1 20.

Input: arr[] = {2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 2 3 7 5 6 4 8 9 10

Naive Approach: 

The simplest approach to solve this problem is to make two arrays/vectors to store the prime and non-prime array elements respectively and print the prime numbers followed by the non-primes numbers. 

Steps to implement this approach:

  • Make two vector prime and nonPrime to store prime and non-prime numbers
  • After that traverse the whole input array and if any number is prime then push that into the prime vector else into the nonPrime vector
  • To check if any number is prime or not, we will take care of many edge cases like 0,1 is not prime, 2,3 is prime, etc..
  • In the last first print elements of the prime vector then print elements of the nonPrime vector

Code to implement the above steps:

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Function to check if a number n
// is a prime number of not
bool isPrime(int n)
{
    // Edges Cases
    if (n <= 1)
        return false;
 
    if (n <= 3)
        return true;
 
    // To skip middle five numbers
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Checks for prime or non prime
    for (int i = 5;
         i * i <= n; i = i + 6) {
 
        // If n is divisible by i
        // or i + 2, return false
        if (n % i == 0
            || n % (i + 2) == 0)
            return false;
    }
 
    // Otherwise, the
    // number is prime
    return true;
}
 
// Function to segregate the primes
// and non-primes present in an array
void segregatePrimeNonPrime(
    int arr[], int N)
{
    //To store Prime Numbers
    vector<int> prime;
    //To store non-prime numbers
    vector<int> nonPrime;
     
  //Traverse the input array
    for(int i=0;i<N;i++){
        if(isPrime(arr[i])){prime.push_back(arr[i]);}
        else{nonPrime.push_back(arr[i]);}
    }
     
  //First print all prime numbers
    for(int i=0;i<prime.size();i++){
        cout<<prime[i]<<" ";
    }
     
  //After printing all prime numbers print all non-prime numbers
    for(int i=0;i<nonPrime.size();i++){
        cout<<nonPrime[i]<<" ";
    }
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    segregatePrimeNonPrime(arr, N);
 
    return 0;
}


Java




import java.util.*;
 
public class Main
{
   
    // Function to check if a number n
    // is a prime number of not
    public static boolean isPrime(int n)
    {
        // Edges Cases
        if (n <= 1)
            return false;
 
        if (n <= 3)
            return true;
 
        // To skip middle five numbers
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        // Checks for prime or non prime
        for (int i = 5; i * i <= n; i = i + 6) {
 
            // If n is divisible by i
            // or i + 2, return false
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }
 
        // Otherwise, the
        // number is prime
        return true;
    }
 
    // Function to segregate the primes
    // and non-primes present in an array
    public static void segregatePrimeNonPrime(int[] arr,
                                              int N)
    {
        // To store Prime Numbers
        ArrayList<Integer> prime = new ArrayList<Integer>();
        // To store non-prime numbers
        ArrayList<Integer> nonPrime
            = new ArrayList<Integer>();
 
        // Traverse the input array
        for (int i = 0; i < N; i++) {
            if (isPrime(arr[i])) {
                prime.add(arr[i]);
            }
            else {
                nonPrime.add(arr[i]);
            }
        }
 
        // First print all prime numbers
        for (int i = 0; i < prime.size(); i++) {
            System.out.print(prime.get(i) + " ");
        }
 
        // After printing all prime numbers print all
        // non-prime numbers
        for (int i = 0; i < nonPrime.size(); i++) {
            System.out.print(nonPrime.get(i) + " ");
        }
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
        int N = arr.length;
 
        segregatePrimeNonPrime(arr, N);
    }
}


Python3




# Python program for the above approach
 
import math
 
# Function to check if a number n is a prime number of not
def isPrime(n):
    # Edges Cases
    if n <= 1:
        return False
 
    if n <= 3:
        return True
 
    # To skip middle five numbers
    if n % 2 == 0 or n % 3 == 0:
        return False
 
    # Checks for prime or non prime
    for i in range(5, int(math.sqrt(n)) + 1, 6):
        # If n is divisible by i or i + 2, return false
        if n % i == 0 or n % (i + 2) == 0:
            return False
 
    # Otherwise, the number is prime
    return True
 
# Function to segregate the primes and non-primes present in an array
def segregatePrimeNonPrime(arr, N):
    # To store Prime Numbers
    prime = []
    # To store non-prime numbers
    nonPrime = []
 
    # Traverse the input array
    for i in range(N):
        if isPrime(arr[i]):
            prime.append(arr[i])
        else:
            nonPrime.append(arr[i])
 
    # First print all prime numbers
    for i in range(len(prime)):
        print(prime[i], end=" ")
 
    # After printing all prime numbers print all non-prime numbers
    for i in range(len(nonPrime)):
        print(nonPrime[i], end=" ")
 
# Driver Code
if __name__ == '__main__':
    arr = [2, 3, 4, 6, 7, 8, 9, 10]
    N = len(arr)
 
    segregatePrimeNonPrime(arr, N)


C#




using System;
using System.Collections.Generic;
 
public class MainClass
{
    // Function to check if a number n
    // is a prime number of not
    public static bool IsPrime(int n)
    {
        // Edge Cases
        if (n <= 1)
            return false;
 
        if (n <= 3)
            return true;
 
        // To skip middle five numbers
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        // Checks for prime or non prime
        for (int i = 5; i * i <= n; i = i + 6)
        {
 
            // If n is divisible by i
            // or i + 2, return false
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }
 
        // Otherwise, the
        // number is prime
        return true;
    }
 
    // Function to segregate the primes
    // and non-primes present in an array
    public static void SegregatePrimeNonPrime(int[] arr, int N)
    {
        // To store Prime Numbers
        List<int> prime = new List<int>();
        // To store non-prime numbers
        List<int> nonPrime = new List<int>();
 
        // Traverse the input array
        for (int i = 0; i < N; i++)
        {
            if (IsPrime(arr[i]))
            {
                prime.Add(arr[i]);
            }
            else
            {
                nonPrime.Add(arr[i]);
            }
        }
 
        // First print all prime numbers
        for (int i = 0; i < prime.Count; i++)
        {
            Console.Write(prime[i] + " ");
        }
 
        // After printing all prime numbers print all
        // non-prime numbers
        for (int i = 0; i < nonPrime.Count; i++)
        {
            Console.Write(nonPrime[i] + " ");
        }
    }
 
    // Driver Code
    public static void Main(string[] args)
    {
        int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
        int N = arr.Length;
 
        SegregatePrimeNonPrime(arr, N);
    }
}


Javascript




<script>
    // Javascript program for the above approach
     
    // Function to check if a number n
    // is a prime number of not
    function isPrime(n) {
        // Edges Cases
        if (n <= 1) {
            return false;
        }
        if (n <= 3) {
            return true;
        }
        // To skip middle five numbers
        if (n % 2 === 0 || n % 3 === 0) {
            return false;
        }
        // Checks for prime or non prime
        for (let i = 5; i * i <= n; i += 6) {
            // If n is divisible by i
            // or i + 2, return false
            if (n % i === 0 || n % (i + 2) === 0) {
                return false;
            }
        }
        // Otherwise, the
        // number is prime
        return true;
    }
     
    // Function to segregate the primes
    // and non-primes present in an array
    function segregatePrimeNonPrime(arr) {
        //To store Prime Numbers
        let prime = [];
        //To store non-prime numbers
        let nonPrime = [];
         
        //Traverse the input array
        for (let i = 0; i < arr.length; i++) {
            if (isPrime(arr[i])) {
                prime.push(arr[i]);
            } else {
                nonPrime.push(arr[i]);
            }
        }
         
        //First print all prime numbers
        for (let i = 0; i < prime.length; i++) {
            document.write(prime[i] + " ");
        }
         
        //After printing all prime numbers print all non-prime numbers
        for (let i = 0; i < nonPrime.length; i++) {
            document.write(nonPrime[i] + " ");
        }
    }
     
    // Driver Code
    let arr = [2, 3, 4, 6, 7, 8, 9, 10];
    segregatePrimeNonPrime(arr);
     
        // This code is contributed by Pushpesh Raj
</script>


Output-

2 3 7 4 6 8 9 10 

Time Complexity: O(N*sqrt(N)), O(N) for traversing the array, and sqrt(N) for finding whether any number is prime or not.
Auxiliary Space: O(N),because of prime and nonPrime vector

Alternate Approach: To optimize the auxiliary space of the above approach, the idea to solve this problem is using the Two-Pointer Approach. Follow the steps below to solve the problem:

  • Initialize two pointers left as 0 and right to the end of the array as (N – 1).
  • Traverse the array until left is less than right and do the following:
    • Keep incrementing the left pointer until the element pointing to the left index is Prime Number.
    • Keep decrementing the right pointer until the element pointing to the left index is a non-Prime Number.
    • If left is less than right then swap arr[left] and arr[right] and increment left and decrement right by 1.
  • After the above steps, print the update array arr[].

Below is the implementation of the above approach:

C++




// C++ program for the above approach
#include <iostream>
using namespace std;
 
// Function to swap two numbers a and b
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// Function to check if a number n
// is a prime number of not
bool isPrime(int n)
{
    // Edges Cases
    if (n <= 1)
        return false;
 
    if (n <= 3)
        return true;
 
    // To skip middle five numbers
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Checks for prime or non prime
    for (int i = 5;
         i * i <= n; i = i + 6) {
 
        // If n is divisible by i
        // or i + 2, return false
        if (n % i == 0
            || n % (i + 2) == 0)
            return false;
    }
 
    // Otherwise, the
    // number is prime
    return true;
}
 
// Function to segregate the primes
// and non-primes present in an array
void segregatePrimeNonPrime(
    int arr[], int N)
{
    // Initialize left and right pointers
    int left = 0, right = N - 1;
 
    // Traverse the array
    while (left < right) {
 
        // Increment left while array
        // element at left is prime
        while (isPrime(arr[left]))
            left++;
 
        // Decrement right while array
        // element at right is non-prime
        while (!isPrime(arr[right]))
            right--;
 
        // If left < right, then swap
        // arr[left] and arr[right]
        if (left < right) {
 
            // Swap arr[left] and arr[right]
            swap(&arr[left], &arr[right]);
            left++;
            right--;
        }
    }
 
    // Print segregated array
    for (int i = 0; i < N; i++)
        cout << arr[i] << " ";
}
 
// Driver Code
int main()
{
    int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    segregatePrimeNonPrime(arr, N);
 
    return 0;
}


Java




// java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
public class GFG {
 
    // Function to check if a number n
    // is a prime number of not
    static boolean isPrime(int n)
    {
        // Edges Cases
        if (n <= 1)
            return false;
 
        if (n <= 3)
            return true;
 
        // To skip middle five numbers
        if (n % 2 == 0 || n % 3 == 0)
            return false;
 
        // Checks for prime or non prime
        for (int i = 5; i * i <= n; i = i + 6) {
 
            // If n is divisible by i
            // or i + 2, return false
            if (n % i == 0 || n % (i + 2) == 0)
                return false;
        }
 
        // Otherwise, the
        // number is prime
        return true;
    }
 
    // Function to segregate the primes
    // and non-primes present in an array
    static void segregatePrimeNonPrime(int arr[], int N)
    {
        // Initialize left and right pointers
        int left = 0, right = N - 1;
 
        // Traverse the array
        while (left < right) {
 
            // Increment left while array
            // element at left is prime
            while (isPrime(arr[left]))
                left++;
 
            // Decrement right while array
            // element at right is non-prime
            while (!isPrime(arr[right]))
                right--;
 
            // If left < right, then swap
            // arr[left] and arr[right]
            if (left < right) {
 
                // Swap arr[left] and arr[right]
                int temp = arr[right];
                arr[right] = arr[left];
                arr[left] = temp;
 
                left++;
                right--;
            }
        }
 
        // Print segregated array
        for (int i = 0; i < N; i++)
            System.out.print(arr[i] + " ");
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
        int N = arr.length;
 
        segregatePrimeNonPrime(arr, N);
    }
}
 
// This code is contributed by Kingash.


Python3




# Python3 program for the above approach
 
# Function to check if a number n
# is a prime number of not
 
 
def isPrime(n):
 
    # Edges Cases
    if (n <= 1):
        return False
 
    if (n <= 3):
        return True
 
    # To skip middle five numbers
    if (n % 2 == 0 or n % 3 == 0):
        return False
 
    # Checks for prime or non prime
    i = 5
 
    while (i * i <= n):
 
        # If n is divisible by i or i + 2,
        # return False
        if (n % i == 0 or n % (i + 2) == 0):
            return False
 
        i += 6
 
    # Otherwise, the number is prime
    return True
 
# Function to segregate the primes and
# non-primes present in an array
 
 
def segregatePrimeNonPrime(arr, N):
 
    # Initialize left and right pointers
    left, right = 0, N - 1
 
    # Traverse the array
    while (left < right):
 
        # Increment left while array element
        # at left is prime
        while (isPrime(arr[left])):
            left += 1
 
        # Decrement right while array element
        # at right is non-prime
        while (not isPrime(arr[right])):
            right -= 1
 
        # If left < right, then swap
        # arr[left] and arr[right]
        if (left < right):
 
            # Swap arr[left] and arr[right]
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
 
    # Print segregated array
    for num in arr:
        print(num, end=" ")
 
 
# Driver code
arr = [2, 3, 4, 6, 7, 8, 9, 10]
N = len(arr)
 
segregatePrimeNonPrime(arr, N)
 
# This code is contributed by girishthatte


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to check if a number n
// is a prime number of not
static bool isPrime(int n)
{
     
    // Edges Cases
    if (n <= 1)
        return false;
 
    if (n <= 3)
        return true;
 
    // To skip middle five numbers
    if (n % 2 == 0 || n % 3 == 0)
        return false;
 
    // Checks for prime or non prime
    for(int i = 5; i * i <= n; i = i + 6)
    {
         
        // If n is divisible by i
        // or i + 2, return false
        if (n % i == 0 || n % (i + 2) == 0)
            return false;
    }
 
    // Otherwise, the
    // number is prime
    return true;
}
 
// Function to segregate the primes
// and non-primes present in an array
static void segregatePrimeNonPrime(int[] arr, int N)
{
     
    // Initialize left and right pointers
    int left = 0, right = N - 1;
 
    // Traverse the array
    while (left < right)
    {
         
        // Increment left while array
        // element at left is prime
        while (isPrime(arr[left]))
            left++;
 
        // Decrement right while array
        // element at right is non-prime
        while (!isPrime(arr[right]))
            right--;
 
        // If left < right, then swap
        // arr[left] and arr[right]
        if (left < right)
        {
             
            // Swap arr[left] and arr[right]
            int temp = arr[right];
            arr[right] = arr[left];
            arr[left] = temp;
 
            left++;
            right--;
        }
    }
 
    // Print segregated array
    for(int i = 0; i < N; i++)
        Console.Write(arr[i] + " ");
}
 
// Driver Code
public static void Main(string[] args)
{
    int[] arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = arr.Length;
 
    segregatePrimeNonPrime(arr, N);
}
}
 
// This code is contributed by ukasp


Javascript




<script>
 
// Javascript program implementation
// of the approach
 
// Function to generate prime numbers
// using Sieve of Eratosthenes
function SieveOfEratosthenes(prime, n)
{
    for(let p = 2; p * p <= n; p++)
    {
          
        // If prime[p] is unchanged,
        // then it is a prime
        if (prime[p] == true)
        {
              
            // Update all multiples of p
            for(let i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
  
// Function to segregate the primes and non-primes
function segregatePrimeNonPrime(prime, arr, N)
{
      
    // Generate all primes till 10^
    SieveOfEratosthenes(prime, 10000000);
  
    // Initialize left and right
    let left = 0, right = N - 1;
  
    // Traverse the array
    while (left < right)
    {
          
        // Increment left while array element
        // at left is prime
        while (prime[arr[left]])
            left++;
  
        // Decrement right while array element
        // at right is non-prime
        while (!prime[arr[right]])
            right--;
  
        // If left < right, then swap arr[left]
        // and arr[right]
        if (left < right)
        {
              
            // Swap arr[left] and arr[right]
            let temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
  
    // Print segregated array
    for(let i = 0; i < N; i++)
         document.write(arr[i] + " ");
}
 
// Driver Code
     
    let prime = Array.from({length: 10000001}, (_, i) => true);
 
    let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ];
    let N = arr.length;
  
    // Function Call
    segregatePrimeNonPrime(prime, arr, N);
          
</script>


Output

2 3 7 6 4 8 9 10

Time Complexity: O(N*sqrt(N))
Auxiliary Space: O(1), since no extra space has been taken.

Efficient Approach: The above approach can be optimized by using the Sieve of Eratosthenes to find whether the number is prime or non-prime in constant time.

Below is the implementation of the above approach: 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
bool prime[10000001];
 
// Function to swap two numbers a and b
void swap(int* a, int* b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// Function to generate prime numbers
// using Sieve of Eratosthenes
void SieveOfEratosthenes(int n)
{
    memset(prime, true, sizeof(prime));
 
    for (int p = 2; p * p <= n; p++) {
 
        // If prime[p] is unchanged,
        // then it is a prime
        if (prime[p] == true) {
 
            // Update all multiples of p
            for (int i = p * p;
                 i <= n; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to segregate the primes
// and non-primes
void segregatePrimeNonPrime(
    int arr[], int N)
{
    // Generate all primes till 10^7
    SieveOfEratosthenes(10000000);
 
    // Initialize left and right
    int left = 0, right = N - 1;
 
    // Traverse the array
    while (left < right) {
 
        // Increment left while array
        // element at left is prime
        while (prime[arr[left]])
            left++;
 
        // Decrement right while array
        // element at right is non-prime
        while (!prime[arr[right]])
            right--;
 
        // If left < right, then swap
        // arr[left] and arr[right]
        if (left < right) {
 
            // Swap arr[left] and arr[right]
            swap(&arr[left], &arr[right]);
            left++;
            right--;
        }
    }
 
    // Print segregated array
    for (int i = 0; i < N; i++)
        cout << arr[i] << " ";
}
 
// Driver code
int main()
{
    int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    segregatePrimeNonPrime(arr, N);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
 
class GFG{
     
// Function to generate prime numbers
// using Sieve of Eratosthenes
public static void SieveOfEratosthenes(boolean[] prime,
                                       int n)
{
    for(int p = 2; p * p <= n; p++)
    {
         
        // If prime[p] is unchanged,
        // then it is a prime
        if (prime[p] == true)
        {
             
            // Update all multiples of p
            for(int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to segregate the primes and non-primes
public static void segregatePrimeNonPrime(boolean[] prime,
                                          int arr[], int N)
{
     
    // Generate all primes till 10^
    SieveOfEratosthenes(prime, 10000000);
 
    // Initialize left and right
    int left = 0, right = N - 1;
 
    // Traverse the array
    while (left < right)
    {
         
        // Increment left while array element
        // at left is prime
        while (prime[arr[left]])
            left++;
 
        // Decrement right while array element
        // at right is non-prime
        while (!prime[arr[right]])
            right--;
 
        // If left < right, then swap arr[left]
        // and arr[right]
        if (left < right)
        {
             
            // Swap arr[left] and arr[right]
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
 
    // Print segregated array
    for(int i = 0; i < N; i++)
        System.out.printf(arr[i] + " ");
}
 
// Driver code
public static void main(String[] args)
{
    boolean[] prime = new boolean[10000001];
    Arrays.fill(prime, true);
    int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = arr.length;
 
    // Function Call
    segregatePrimeNonPrime(prime, arr, N);
}
}
 
// This code is contributed by girishthatte


Python3




# Python3 program for the above approach
 
# Function to generate prime numbers
# using Sieve of Eratosthenes
def SieveOfEratosthenes(prime, n):
     
    p = 2
     
    while (p * p <= n):
         
        # If prime[p] is unchanged,
        # then it is a prime
        if (prime[p] == True):
             
            # Update all multiples of p
            i = p * p
             
            while (i <= n):
                prime[i] = False
                i += p
                 
        p += 1
 
# Function to segregate the primes and non-primes
def segregatePrimeNonPrime(prime, arr, N):
 
    # Generate all primes till 10^7
    SieveOfEratosthenes(prime, 10000000)
 
    # Initialize left and right
    left, right = 0, N - 1
 
    # Traverse the array
    while (left < right):
 
        # Increment left while array element
        # at left is prime
        while (prime[arr[left]]):
            left += 1
 
        # Decrement right while array element
        # at right is non-prime
        while (not prime[arr[right]]):
            right -= 1
 
        # If left < right, then swap arr[left]
        # and arr[right]
        if (left < right):
             
            # Swap arr[left] and arr[right]
            arr[left], arr[right] = arr[right], arr[left]
            left += 1
            right -= 1
 
    # Print segregated array
    for num in arr:
        print(num, end = " ")
 
# Driver code
arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]
N = len(arr)
prime = [True] * 10000001
 
# Function Call
segregatePrimeNonPrime(prime, arr, N)
 
# This code is contributed by girishthatte


C#




// C# program for the above approach
using System;
 
class GFG{
     
// Function to generate prime numbers
// using Sieve of Eratosthenes
public static void SieveOfEratosthenes(bool[] prime,
                                       int n)
{
    for(int p = 2; p * p <= n; p++)
    {
         
        // If prime[p] is unchanged,
        // then it is a prime
        if (prime[p] == true)
        {
             
            // Update all multiples of p
            for(int i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
 
// Function to segregate the primes and non-primes
public static void segregatePrimeNonPrime(bool[] prime,
                                          int []arr, int N)
{
     
    // Generate all primes till 10^
    SieveOfEratosthenes(prime, 10000000);
 
    // Initialize left and right
    int left = 0, right = N - 1;
 
    // Traverse the array
    while (left < right)
    {
         
        // Increment left while array element
        // at left is prime
        while (prime[arr[left]])
            left++;
 
        // Decrement right while array element
        // at right is non-prime
        while (!prime[arr[right]])
            right--;
 
        // If left < right, then swap arr[left]
        // and arr[right]
        if (left < right)
        {
             
            // Swap arr[left] and arr[right]
            int temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
 
    // Print segregated array
    for(int i = 0; i < N; i++)
        Console.Write(arr[i] + " ");
}
 
// Driver code
public static void Main(String[] args)
{
    bool[] prime = new bool[10000001];
    for(int i = 0; i < prime.Length; i++)
        prime[i] = true;
         
    int []arr = { 2, 3, 4, 6, 7, 8, 9, 10 };
    int N = arr.Length;
 
    // Function Call
    segregatePrimeNonPrime(prime, arr, N);
}
}
 
// This code is contributed by Princi Singh


Javascript




// Javascript program for the above approach
 
// Function to generate prime numbers
// using Sieve of Eratosthenes
function SieveOfEratosthenes(prime, n)
{
    for(let p = 2; p * p <= n; p++)
    {
          
        // If prime[p] is unchanged,
        // then it is a prime
        if (prime[p] == true)
        {
              
            // Update all multiples of p
            for(let i = p * p; i <= n; i += p)
                prime[i] = false;
        }
    }
}
  
// Function to segregate the primes and non-primes
function segregatePrimeNonPrime(prime, arr, N)
{
      
    // Generate all primes till 10^
    SieveOfEratosthenes(prime, 10000000);
  
    // Initialize left and right
    let left = 0, right = N - 1;
  
    // Traverse the array
    while (left < right)
    {
          
        // Increment left while array element
        // at left is prime
        while (prime[arr[left]])
            left++;
  
        // Decrement right while array element
        // at right is non-prime
        while (!prime[arr[right]])
            right--;
  
        // If left < right, then swap arr[left]
        // and arr[right]
        if (left < right)
        {
              
            // Swap arr[left] and arr[right]
            let temp = arr[left];
            arr[left] = arr[right];
            arr[right] = temp;
            left++;
            right--;
        }
    }
  
    // Print segregated array
    for(let i = 0; i < N; i++)
        console.log(arr[i] + " ");
}
  
  // Driver Code
     
    let prime = Array.from({length: 10000001},
                (_, i) => true);
    let arr = [ 2, 3, 4, 6, 7, 8, 9, 10 ];
    let N = arr.length;
  
    // Function Call
    segregatePrimeNonPrime(prime, arr, N);
  


Output

2 3 7 6 4 8 9 10

Time Complexity: O(N*log(log(N)))
Auxiliary Space: O(N)
 



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads