text: Sort prime numbers of an array in descending order | C ++ implementation of the approach ; false here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function that sorts all the prime numbers from the array in descending ; this vector will contain prime numbers to sort ; if the element is prime ; update the array elements ; Driver code ; print the results .
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool prime [ 100005 ] ; void SieveOfEratosthenes ( int n ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= n ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= n ; i += p ) prime [ i ] = false ; } } } void sortPrimes ( int arr [ ] , int n ) { SieveOfEratosthenes ( 100005 ) ; vector < int > v ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) v . push_back ( arr [ i ] ) ; } sort ( v . begin ( ) , v . end ( ) , greater < int > ( ) ) ; int j = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) arr [ i ] = v [ j ++ ] ; } } int main ( ) { int arr [ ] = { 4 , 3 , 2 , 6 , 100 , 17 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; sortPrimes ( arr , n ) ; for ( int i = 0 ; i < n ; i ++ ) { cout << arr [ i ] << " ▁ " ; } return 0 ; }