Sort all special primes in their relative positions | C # 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 List and set arr [ i ] to - 1 ; Sort the special primes ; Position of a special prime ; Driver code
using System ; using System . Collections . Generic ; using System . Linq ; class GFG { static void sieveOfEratosthenes ( bool [ ] 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 = arr . Max ( ) ; bool [ ] prime = new bool [ maxVal + 1 ] ; for ( int i = 0 ; i < prime . Length ; i ++ ) prime [ i ] = true ; sieveOfEratosthenes ( prime , maxVal ) ; List < int > list = new List < int > ( ) ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . Add ( arr [ i ] ) ; arr [ i ] = - 1 ; } } list . Sort ( ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == - 1 ) Console . Write ( list [ j ++ ] + " ▁ " ) ; else Console . Write ( arr [ i ] + " ▁ " ) ; } } public static void Main ( String [ ] args ) { int [ ] arr = { 31 , 5 , 2 , 1 , 7 } ; int n = arr . Length ; sortSpecialPrimes ( arr , n ) ; } }