Advertisement
saurav_kalsoor

Sort By Indices - JAVA

Jan 24th, 2022
118
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Author : Saurav Kalsoor
  2. // Sort By Indices - 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.         int m = sc.nextInt();
  12.         ArrayList<Integer> arr = new ArrayList<>();
  13.         ArrayList<Integer> indices = new ArrayList<>();
  14.  
  15.         for(int i=0; i < n; i++) {
  16.             int input = sc.nextInt();
  17.             arr.add(input);
  18.         }
  19.  
  20.         for(int i=0; i < m; i++) {
  21.             int input = sc.nextInt();
  22.             indices.add(input);
  23.         }
  24.  
  25.         ArrayList<Integer> result = sortByIndices(arr, indices, n, m);
  26.        
  27.         for(int i=0; i < n; i++)
  28.             System.out.print(result.get(i) + " ");
  29.        
  30.         System.out.println();
  31.     }
  32.  
  33.     public static ArrayList<Integer> sortByIndices(ArrayList<Integer> arr, ArrayList<Integer> indices, int n, int m){
  34.         ArrayList<Integer> sortDesc = new ArrayList<Integer>();
  35.         ArrayList<Integer> sortAsc = new ArrayList<Integer>();
  36.  
  37.         HashSet<Integer> indicesSet = new HashSet<Integer>();
  38.  
  39.         for(int i=0; i < m; i++){
  40.             indicesSet.add(indices.get(i));
  41.         }
  42.  
  43.         for(int i=0; i < n; i++){
  44.             if(indicesSet.contains(i)){
  45.                 sortDesc.add(arr.get(i));
  46.             }else{
  47.                 sortAsc.add(arr.get(i));
  48.             }
  49.         }
  50.    
  51.         Collections.sort(sortDesc, Collections.reverseOrder());
  52.         Collections.sort(sortAsc);
  53.  
  54.         ArrayList<Integer> result = new ArrayList<Integer>();
  55.  
  56.         int j = 0, k = 0;
  57.         for(int i=0; i < n; i++){
  58.             if(indicesSet.contains(i)){
  59.                 result.add(sortDesc.get(j));
  60.                 j++;
  61.             }else{
  62.                 result.add(sortAsc.get(k));
  63.                 k++;
  64.             }
  65.         }
  66.  
  67.         return result;
  68.     }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement