排序2维java数组 [英] sorting 2 dimensional java array
问题描述
我已经实现了冒泡排序来对二维java long [] []
进行排序但我的上帝很慢,我将需要禁食算法,因为
i将生成一个数组最大堆大小jvm将允许我,
I have implemented bubble sort to sort a two dimensional java long [][] but my god is it slow, I will be needing the fasted algorithm possible as i will be generating a array of the max heap size jvm will allow me,
所以我认为最好和最快的方法是使用inbuild java Arrays.sort
So i think the best and fastest way would be to use the inbuild java Arrays.sort
我不介意它是否只能排在第一列,因为我可以改变我的程序以适应,
我遇到过这个,但我不熟悉comaparator,
I dont mind if it can only sort on column one as i can change my program to suit, I came across this but am not to familar with comaparator,
这将允许我对一个整数的维数组排序,有没有人知道如何改变它以允许多头?,我做了思想家用它没有欢乐。
this will allow me to sort a dimensional array of integers, does anyone know how to change this to allow longs?, i did thinker around with it with no joy yet.
int d2 [][] = {{1,43},{26,98},{44,398},{11,34},{17,32}};
java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return b[0] - a[0];
}
});
我想排序说
long d2L [][] = {{1,43},{26,98},{44,398},{11,34},{17,32}};
铸造不是一个选项,因为数字是巨大的
casting is not an option as the numbers a massive
此外,如果有人认为这是一个更快的方法来排序我所有的耳朵:)
Also if anyone thinks theres a faster method to sort im all ears:)
推荐答案
这基于所有列排序在O(NlogN)中,即非常快:
This sorts based on all columns in O(NlogN), i.e. really fast:
import java.util.*;
class Compare2DArray implements Comparator {
public int compare(Object a, Object b) {
int aa[] = (int[]) a;
int bb[] = (int[]) b;
for (int i = 0; i < aa.length && i < bb.length; i++)
if (aa[i] != bb[i])
return aa[i] - bb[i];
return aa.length - bb.length;
}
}
class sort2d {
public static void main(String args[]) {
int d2 [][] = {{1,43},{26,98},{44,398},{11,34},{17,32}};
Arrays.sort(d2, new Compare2DArray());
for (int i = 0; i < d2.length; i++) {
for (int j = 0; j < d2[i].length; j++)
System.out.print(d2[i][j] + " ");
System.out.println();
}
}
}
或者您可以使用泛型来避免cast:
Or you could use generics to avoid casting:
class Compare2DArray implements Comparator<int[]> {
public int compare(int a[], int b[]) {
for (int i = 0; i < a.length && i < b.length; i++)
if (a[i] != b[i])
return a[i] - b[i];
return a.length - b.length;
}
}
这篇关于排序2维java数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!