Sort only non | Python3 program to sort only non primes ; Create a boolean array " prime [ 0 . . n ] " and initialize all entries it as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function to print the array such that only non primes are sorted ; list v will store all non prime numbers ; If not prime , insert into list ; sorting list of non primes ; print the required array ; Driver code
from math import sqrt NEW_LINE prime = [ 0 ] * 100005 NEW_LINE def SieveOfEratosthenes ( n ) : NEW_LINE INDENT for i in range ( len ( prime ) ) : NEW_LINE INDENT prime [ i ] = True NEW_LINE DEDENT prime [ 1 ] = False NEW_LINE for p in range ( 2 , int ( sqrt ( n ) ) + 1 ) : NEW_LINE INDENT if prime [ p ] == True : NEW_LINE INDENT for i in range ( p * 2 , n , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT DEDENT DEDENT def sortedArray ( arr , n ) : NEW_LINE INDENT SieveOfEratosthenes ( 100005 ) NEW_LINE v = [ ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prime [ arr [ i ] ] == 0 : NEW_LINE INDENT v . append ( arr [ i ] ) NEW_LINE DEDENT DEDENT v . sort ( ) NEW_LINE j = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prime [ arr [ i ] ] == True : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( v [ j ] , end = " ▁ " ) NEW_LINE j += 1 NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT n = 6 NEW_LINE arr = [ 100 , 11 , 500 , 2 , 17 , 1 ] NEW_LINE sortedArray ( arr , n ) NEW_LINE DEDENT