Sort all special primes in their relative positions | C ++ implementation of the 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; 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 ; } } } void sortSpecialPrimes ( int arr [ ] , int n ) { int maxVal = * max_element ( arr , arr + n ) ; bool prime [ maxVal + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; sieveOfEratosthenes ( prime , maxVal ) ; vector < int > list ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] && prime [ arr [ i ] - 2 ] ) { list . push_back ( arr [ i ] ) ; arr [ i ] = -1 ; } } sort ( list . begin ( ) , list . end ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] == -1 ) cout << list [ j ++ ] << " ▁ " ; else cout << arr [ i ] << " ▁ " ; } } int main ( ) { int arr [ ] = { 31 , 5 , 2 , 1 , 7 } ; int n = sizeof ( arr ) / sizeof ( int ) ; sortSpecialPrimes ( arr , n ) ; return 0 ; }