我有一个包含2行和n列的2D数组。
我正在尝试使用内置的Arrays.sort方法对数组进行排序,但我正在努力使用比较器。我想按第一行对2D数组进行排序,以便第二行元素将保留与它们对齐的原始元素,即。将列保持在一起。
例如原始数组:
int[] unsortedArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4},
排序数组:
int[] unsortedArray = new int[][]{
{ 0, 1, 2, 3, 3, 6},
{ 4, 6, 6, 1, 2, 2},
这样做的最佳方法是什么? 欢呼声。
答案 0 :(得分:0)
尝试以下方法:
免责声明:未经测试:)
myarray = new int[10][2];
// populate the array here
Arrays.sort(myarray, new Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a[0] > b[0])
return 1;
else if (a[0] < b[0])
return -1;
else {
return 0;
}
}
};
答案 1 :(得分:0)
您必须编写自定义排序。查看Comparable和Comparator。
有些事情:
public class MyComparator implements Comparator<T[]> {
int columnToSortOn;
public MyComparator(int columnToSortOn) {
this.columnToSortOn = columnToSortOn;
}
@Override
public int compare(T[] array1, T[] array2) {
return array1[columnToSortOn].compareTo(array2[columnToSortOn]);
}
}
答案 2 :(得分:0)
以下是保持列对齐的另一种方法。这使用一个简单的类来保存两个列元素。
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}
逐一将每列(来自子阵列1和2)放在此对象中,并立即放入Map<Integer,List<TwoInts>>
。关键是来自intArrayArray[0]
的元素,值是TwoInts
的列表,因为{{和(在您的示例代码中)可能是{{ 1}}。
然后迭代遍历地图的键集,并将它们替换为数组。
完整代码:
intArrayArray[0]
输出:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/**
<P>{@code java SortOneArrayKeepSecondArrayElementsAligned}</P>
**/
public class SortOneArrayKeepSecondArrayElementsAligned {
public static final void main(String[] ignored) {
int[][] intArrayArray = new int[][]{
{ 6, 3, 1, 2, 3, 0},
{ 2, 1, 6, 6, 2, 4}};
output2DArray("Unsorted", intArrayArray);
Map<Integer,List<TwoInts>> twoIntMap = new TreeMap<Integer,List<TwoInts>>();
for(int i = 0; i < intArrayArray[0].length; i++) {
int intIn0 = intArrayArray[0][i];
if(!twoIntMap.containsKey(intIn0)) {
List<TwoInts> twoIntList = new ArrayList<TwoInts>(intArrayArray.length);
twoIntList.add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
twoIntMap.put(intIn0, twoIntList);
} else {
twoIntMap.get(intIn0).add(new TwoInts(intArrayArray[0][i], intArrayArray[1][i]));
}
}
int idx = 0;
Iterator<Integer> itr2i = twoIntMap.keySet().iterator();
while(itr2i.hasNext()) {
List<TwoInts> twoIntList = twoIntMap.get(itr2i.next());
for(TwoInts twoi : twoIntList) {
intArrayArray[0][idx] = twoi.aElement;
intArrayArray[1][idx++] = twoi.bElement;
}
}
output2DArray("Sorted", intArrayArray);
}
private static final void output2DArray(String description, int[][] twoD_array) {
System.out.println(description + ":");
System.out.println("0: " + Arrays.toString(twoD_array[0]));
System.out.println("1: " + Arrays.toString(twoD_array[1]));
System.out.println();
}
}
class TwoInts {
public final int aElement;
public final int bElement;
public TwoInts(int a_element, int b_element) {
aElement = a_element;
bElement = b_element;
}
}