0

Can I sort an array based on second arrray?

I mean, lets say

a[]=[2,5,4,3]
c[]=[800,1600,200,400]

c[i] and a[i] are related for same i.

I want to sort a such that a[]=[5,2,3,4] in decreasing order of values stored in c because 5->1600 , 2->800 and so on.

Can it be done in a single line, like below (below is just structure of answer I am expecting)

Arrays.sort(a, (i, j) -> Integer.compare(c[j], c[i]))

I am doing it via lengthy method of using extra space.

8
  • 1
    yeap: but first array must be an Integer wrapper for it to work Arrays.sort(a, (i, j) -> Integer.compare(c[Arrays.asList(a).indexOf(j)], c[Arrays.asList(a).indexOf(i)])); If that is acceptable let me know, I can add it as an answer Commented Oct 22, 2024 at 15:46
  • @JorgeCampos wouldn't this approach not work for duplicate values? Commented Oct 22, 2024 at 15:53
  • 3
    If c[i] and a[i] are related, then why don't you create a class or record for it? Example: record Employee(int id, int salary) {}. Commented Oct 22, 2024 at 15:55
  • 2
    I'm pretty certain you can achieve this in one line with IntStream shenanigans. It'll be a long and awkward line, more difficult to understand and probably less efficient than a more explicit solution -- like most applications of streams that aren't aimed at one of the "sweet spots" of the API. Commented Oct 22, 2024 at 15:57
  • 1
    After some shenanigans with IntStream here is a one liner solution taking into account duplicates: int[] result = new int[4]; result = IntStream.range(0, a.length).boxed().sorted((i, j) -> Integer.compare(c[j], c[i])).map(i -> a[i]).mapToInt(Integer::intValue).toArray(); Commented Oct 22, 2024 at 18:21

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.