-4

I am trying to write a function that takes two parameters, int[] arr1 and int[] arr2. Then, it should sort arr1 in the order given in arr2. For example, if arr1 is [5,7,9,10,7,5] and arr2 is [7,9,10,5], the function should return [7,7,9,10,5,5], sorting arr1 in the order elements in arr2 are indexed.

I wrote my code as below, but I keep on getting an error at Arrays.sort. I think I am using lambda incorrectly. Can you specify what I am doing wrong?

public int[] relativeSortArray(int[] arr1, int[] arr2) {

    Map<Integer, Integer> elemToInd = new HashMap<Integer, Integer>();
    for (int i = 0; i < arr2.length; i++) {
        elemToInd.put(arr2[i], i);
    }

    Arrays.sort(arr1, (int n1, int n2) -> elemToInd.get(n1) - elemToInd.get(n2));

    return arr1;
}
6
  • 1
    Just a question: why would you want to "copy" a sort order that you already have (i.e., why not just use arr2)? Commented Oct 12, 2019 at 5:24
  • 2
    primitive types can't be used with generics Commented Oct 12, 2019 at 5:27
  • @ernest_k I thought it would increase time complexity to go through arr2 to find index of each element every time I do compare, doesn't it? Commented Oct 12, 2019 at 5:28
  • does arr2[] always holds indices of elements? I.e., always has numbers between 0..N-1 (N is the size of arr1[]) and no duplicates? If that's the case, it's easy to create a new array and copy according to the indices of arr2[] Commented Oct 12, 2019 at 5:40
  • @nimrodm arr2 has no duplicates but arr1 can have duplicates. e.g arr1 [0,0,0,100,100], arr2 [100,0] => output [100,100,0,0,0] Commented Oct 12, 2019 at 5:45

2 Answers 2

3

You can change the type of arr1 (and of course return type), so that types conform (to Integer[]) and write simply:

Arrays.sort(arr1, Comparator.comparing(elemToInd::get));

But what you're doing is quite confusing. You cannot use generics with primitives, just reach to Arrays clas for helper methods. On the other hand for collections you can invoke sort method on them.

Sign up to request clarification or add additional context in comments.

Comments

0
 package java.util;   
 public static <T> void sort(T[] a, Comparator<? super T> c)

you can see when you use this method, Comparator type must super T ,so type of arr must be using Integer

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.