Sort all special primes in their relative positions | Java implementation of the above approach ; 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 ArrayList and set arr [ i ] to - 1 ; Sort the special primes ; Position of a special prime ; Driver code
import java . util . * ; class GFG { static void sieveOfEratosthenes ( boolean prime [ ] , int n ) { prime [ 0 ] = prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * p ; i <= n ; i += p ) prime [ i ] = false ; } } } static void sortSpecialPrimes ( int arr [ ] , int n ) { int maxVal = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; boolean [ ] prime = new boolean [ maxVal + 1 ] ; for ( int i = 0 ; i < prime . length ; i ++ ) prime [ i ] = true ; sieveOfEratosthenes ( prime , maxVal ) ; Vector < Integer > list = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . add ( arr [ i ] ) ; arr [ i ] = - 1 ; } } Collections . sort ( list ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == - 1 ) System . out . print ( list . get ( j ++ ) + " ▁ " ) ; else System . out . print ( arr [ i ] + " ▁ " ) ; } } public static void main ( String [ ] args ) { int arr [ ] = { 31 , 5 , 2 , 1 , 7 } ; int n = arr . length ; sortSpecialPrimes ( arr , n ) ; } }