Sort only non | 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 . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print the array such that only non primes are sorted ; vector v will store all non prime numbers ; If not prime , insert into vector ; sorting vector of non primes ; print the required array ; Driver Code
prime = new Array ( 100005 ) ; function SieveOfEratosthenes ( n ) { prime . fill ( true ) ; prime [ 1 ] = false ; for ( var p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } function sortedArray ( arr , n ) { SieveOfEratosthenes ( 100005 ) ; var v = [ ] ; for ( var i = 0 ; i < n ; ++ i ) { if ( prime [ arr [ i ] ] == 0 ) v . push ( arr [ i ] ) ; } v . sort ( ) ; var j = 0 ; 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 ) ;