说我有这两个数组:
int[] foo = new int[] {3, 4, 2, 1, 5};
int[] bar = new int[] {1, 2, 3, 4, 5};
如果我对foo
进行排序,我想将应用于其的相同互换应用于bar
。
所以我会得到这个:
int[] new_foo = new int[] {1, 2, 3, 4, 5};
int[] new_bar = new int[] {4, 3, 1, 2, 5};
我如何轻松实现这一点,是否有任何可重复使用的java方法,所以我不必自己去实现它?
答案 0 :(得分:3)
如果数组1和2中的数字属于一起,则可以使用两个所属字段创建一个对象。让我们称之为" Pair"它具有属性" foo" &" bar"。然后我会创建这些对并按照它们的foo属性对它们进行排序:
public class SortPairs {
static class Pair {
final int foo;
final int bar;
Pair(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
@Override
public String toString() {
return "Pair{" + "foo=" + foo + ", bar=" + bar + '}';
}
}
public static void main(String[] args) {
List<Pair> pairs = Arrays.asList(
new Pair(3, 1),
new Pair(4, 2),
new Pair(2, 3),
new Pair(1, 4),
new Pair(5, 5));
System.out.println(pairs);
Collections.sort(pairs, (pair1, pair2) -> pair1.foo - pair2.foo);
System.out.println(pairs);
}
}
答案 1 :(得分:1)
如果您了解如何对一个数组进行排序,那么只需应用&#34;条目交换&#34;在第一个数组中交换单元格时到第二个数组。
伪代码(因为这似乎是一个家庭作业问题):
sort code
if (need to swap cells i and j in Foo) {
swap foo cell i with cell j
swap bar cell i with cell j
}
loop end