Advertisement
saurav_kalsoor

Sort By Primes - JAVA

Jan 25th, 2022
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // Sort By Primes - JAVA
  3.  
  4. import java.util.*;
  5.  
  6. public class Test {
  7.    
  8.     static Scanner sc = new Scanner(System.in);
  9.     public static void main(String[] args) {
  10.         int n = sc.nextInt();
  11.  
  12.         ArrayList<Integer> arr = new ArrayList<>();
  13.  
  14.         for(int i=0; i < n; i++) {
  15.             int input = sc.nextInt();
  16.             arr.add(input);
  17.         }
  18.  
  19.         ArrayList<Integer> result = sortPrimeNonPrime(arr, n);
  20.        
  21.         for(int i=0; i < n; i++)
  22.             System.out.print(result.get(i) + " ");
  23.        
  24.         System.out.println();
  25.     }
  26.  
  27.     public static ArrayList<Integer> sortPrimeNonPrime(ArrayList<Integer> arr, int n){
  28.  
  29.         int maxLimit = 10001;
  30.         HashSet<Integer> primesSet = new HashSet<>();
  31.         boolean[] isPrime = new boolean[maxLimit];
  32.  
  33.         for(int i=2; i < maxLimit; i++) isPrime[i] = true;
  34.  
  35.         for(int i=2; i < maxLimit; i++){
  36.             if(isPrime[i]){
  37.                 primesSet.add(i);
  38.                 for(int j = i*i ; j < maxLimit; j += i)
  39.                     isPrime[j] = false;
  40.             }
  41.         }
  42.  
  43.         ArrayList<Integer> primes = new ArrayList<Integer>();
  44.         ArrayList<Integer> nonPrimes = new ArrayList<Integer>();
  45.  
  46.         for(int i=0; i < n; i++){
  47.             if(primesSet.contains(arr.get(i))){
  48.                 primes.add(arr.get(i));
  49.             }else{
  50.                 nonPrimes.add(arr.get(i));
  51.             }
  52.         }
  53.    
  54.         Collections.sort(primes);
  55.         Collections.sort(nonPrimes, Collections.reverseOrder());
  56.        
  57.         ArrayList<Integer> result = new ArrayList<Integer>();
  58.  
  59.         int j = 0, k = 0;
  60.         for(int i=0; i < n; i++){
  61.             if(primesSet.contains(arr.get(i))){
  62.                 result.add(primes.get(j));
  63.                 j++;
  64.             }else{
  65.                 result.add(nonPrimes.get(k));
  66.                 k++;
  67.             }
  68.         }
  69.  
  70.         return result;
  71.     }
  72. }
  73.  
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement