Segregate Prime and Non-Prime Numbers in an array

09 Jun, 2021
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 20Explanation: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 to store the prime and non-prime array elements respectively and print the prime numbers followed by the non-primes numbers. 
Time Complexity: O(N*sqrt(N))Auxiliary Space: O(N)
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.
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++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Function to swap two numbers a and bvoid swap(int* a, int* b){    int temp = *a;    *a = *b;    *b = temp;} // Function to check if a number n// is a prime number of notbool 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 arrayvoid 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) {             // Swapp 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 Codeint main(){    int arr[] = { 2, 3, 4, 6, 7, 8, 9, 10 };    int N = sizeof(arr) / sizeof(arr[0]);     segregatePrimeNonPrime(arr, N);     return 0;}
// java program for the above approachimport 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) {                 // Swapp 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 program for the above approach # Function to check if a number n# is a prime number of notdef 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 arraydef 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):             # Swapp 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 codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr) segregatePrimeNonPrime(arr, N) # This code is contributed by girishthatte
// C# program for the above approachusing System; class GFG{ // Function to check if a number n// is a prime number of notstatic 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 arraystatic 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)        {                         // Swapp 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 Codepublic 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
<script> // Javascript program implementation// of the approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction 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-primesfunction 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>
2 3 7 6 4 8 9 10
 
Time Complexity: O(N*sqrt(N))Auxiliary Space: O(1)
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++
Java
Python3
C#
Javascript
// 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 bvoid swap(int* a, int* b){    int temp = *a;    *a = *b;    *b = temp;} // Function to generate prime numbers// using Sieve of Eratosthenesvoid 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-primesvoid 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 codeint 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 program for the above approachimport java.util.*; class GFG{     // Function to generate prime numbers// using Sieve of Eratosthenespublic 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-primespublic 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 codepublic 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 program for the above approach # Function to generate prime numbers# using Sieve of Eratosthenesdef 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-primesdef 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 codearr = [ 2, 3, 4, 6, 7, 8, 9, 10 ]N = len(arr)prime = [True] * 10000001 # Function CallsegregatePrimeNonPrime(prime, arr, N) # This code is contributed by girishthatte
// C# program for the above approachusing System; class GFG{     // Function to generate prime numbers// using Sieve of Eratosthenespublic 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-primespublic 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 codepublic 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
<script> // Javascript program for the above approach // Function to generate prime numbers// using Sieve of Eratosthenesfunction 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-primesfunction 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>
2 3 7 6 4 8 9 10
 
Time Complexity: O(N*log(log(N)))Auxiliary Space: O(N)
 
Kingash
girishthatte
ukasp
princi singh
souravghosh0416
susmitakundugoaldanga
ankita_saini
interview-preparation
Paytm
Prime Number
sieve
two-pointer-algorithm
Arrays
Mathematical
Paytm
two-pointer-algorithm
Arrays
Mathematical
Prime Number
sieve
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.