-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;
}
Andronicus
  • 25,419
  • 17
  • 47
  • 88
wWw
  • 147
  • 9
  • 1
    Just a question: why would you want to "copy" a sort order that you already have (i.e., why not just use `arr2`)? – ernest_k Oct 12 '19 at 05:24
  • 2
    primitive types can't be used with generics – Lino Oct 12 '19 at 05: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? – wWw Oct 12 '19 at 05: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[] – nimrodm Oct 12 '19 at 05: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] – wWw Oct 12 '19 at 05:45
  • @wWw: I was hoping arr2[] would have indices into arr1[] like your original example. The [100,0] example kills this assumption. So I guess you have to use the hash and convert the int[] to Integer[] or List – nimrodm Oct 12 '19 at 18:21

2 Answers2

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.

Andronicus
  • 25,419
  • 17
  • 47
  • 88
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