Sort all special primes in their relative positions | Function for the Sieve of Eratosthenes ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p greater than or equal to the square of it numbers which are multiple of p and are less than p ^ 2 are already been marked . ; Function to sort the special primes in their relative positions ; Maximum element from the array ; prime [ i ] will be true if i is a prime ; To store the special primes from the array ; If current element is a special prime ; Add it to the List and set arr [ i ] to - 1 ; Sort the special primes ; Position of a special prime ; Driver Code
function sieveOfEratosthenes ( prime , n ) { prime [ 0 ] = prime [ 1 ] = false ; 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 sortSpecialPrimes ( arr , n ) { let maxVal = Math . max ( ... arr ) ; let prime = Array . from ( { length : maxVal + 1 } , ( _ , i ) => 0 ) ; for ( let i = 0 ; i < prime . length ; i ++ ) prime [ i ] = true ; sieveOfEratosthenes ( prime , maxVal ) ; let list = [ ] ; for ( let i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . push ( arr [ i ] ) ; arr [ i ] = - 1 ; } } list . sort ( ( a , b ) => a - b ) ; let j = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == - 1 ) document . write ( list [ j ++ ] + " " ) ; else document . write ( arr [ i ] + " " ) ; } } let arr = [ 31 , 5 , 2 , 1 , 7 ] ; let n = arr . length ; sortSpecialPrimes ( arr , n ) ;