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