Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Author : Saurav Kalsoor
- // Sort By Indices - JAVA
- import java.util.*;
- public class Test {
- static Scanner sc = new Scanner(System.in);
- public static void main(String[] args) {
- int n = sc.nextInt();
- int m = sc.nextInt();
- ArrayList<Integer> arr = new ArrayList<>();
- ArrayList<Integer> indices = new ArrayList<>();
- for(int i=0; i < n; i++) {
- int input = sc.nextInt();
- arr.add(input);
- }
- for(int i=0; i < m; i++) {
- int input = sc.nextInt();
- indices.add(input);
- }
- ArrayList<Integer> result = sortByIndices(arr, indices, n, m);
- for(int i=0; i < n; i++)
- System.out.print(result.get(i) + " ");
- System.out.println();
- }
- public static ArrayList<Integer> sortByIndices(ArrayList<Integer> arr, ArrayList<Integer> indices, int n, int m){
- ArrayList<Integer> sortDesc = new ArrayList<Integer>();
- ArrayList<Integer> sortAsc = new ArrayList<Integer>();
- HashSet<Integer> indicesSet = new HashSet<Integer>();
- for(int i=0; i < m; i++){
- indicesSet.add(indices.get(i));
- }
- for(int i=0; i < n; i++){
- if(indicesSet.contains(i)){
- sortDesc.add(arr.get(i));
- }else{
- sortAsc.add(arr.get(i));
- }
- }
- Collections.sort(sortDesc, Collections.reverseOrder());
- Collections.sort(sortAsc);
- ArrayList<Integer> result = new ArrayList<Integer>();
- int j = 0, k = 0;
- for(int i=0; i < n; i++){
- if(indicesSet.contains(i)){
- result.add(sortDesc.get(j));
- j++;
- }else{
- result.add(sortAsc.get(k));
- k++;
- }
- }
- return result;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement