java的:排序ARRAY1基于数组2 [英] java: sort array1 based on array2
问题描述
感谢 Zirak 的在我的 previous帖子我实现JavaScript中的以下内容:
VAR ARR1 = [0,1,2,3];
VAR ARR2 =AC,BC,广告,E];
VAR的结果= ARR1的.sort(功能(I,J){返回ARR2 [I] .localeCompare(ARR2 [J])})
文件撰写(结果);
要实现这一目标的方式是相当紧凑在JavaScript中,可以这样的Java实现也可以通过这样的简单实现?我只能想到实施类似如下的界面可比的:
公共类testCompare {
公共静态的String [] = ARR2 {AC,BC,广告,E};
公共静态的OBJ [] ARR1 = {新的Obj(0),新的OBJ(1),新的OBJ(2),新的OBJ(3)};
静态类的OBJ实现可比{
INT索引= 0;
公开的OBJ(int i)以{
指数= I;
}
@覆盖
公众诠释的compareTo(对象o){
返回ARR2 [指数] .compareTo(ARR2 [((OBJ)O)的.index]);
}
}
}
但如果数组包含X项目很多,那么我将不得不创建点¯x许多OBJ文件,有另一种方式,我可以做到这一点更简单?另一个问题是,如果我做上面的方法会是什么时间复杂度为无论是在Java和JavaScript中的排序,就都为O(n ^ 2)
?非常感谢
公共类MyComparator实现比较<整数GT; {
@覆盖
公众诠释比较(整数I1,I2整数){
返回ARR2 [i1.intValue()]的compareTo(ARR2 [i2.intValue()])。
}
}Arrays.sort(ARR1,新MyComparator());
这是JavaScript的排序是一样的。被使用的比较对象作为回调函数是在JavaScript中使用。
Thanks for the help from Zirak In my previous post i implemented the following in JavaScript:
var arr1 =[0,1,2,3];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );
The way to achieve this is quite compact in JavaScript, can a java implementation of this be also achieved by such simplicity? I could only think of implementing the Comparable interface like the following:
public class testCompare {
public static String[] arr2={"ac", "bc", "ad", "e"};
public static Obj[] arr1={new Obj(0), new Obj(1), new Obj(2), new Obj(3)};
static class Obj implements Comparable{
int index=0;
public Obj(int i){
index=i;
}
@Override
public int compareTo(Object o) {
return arr2[index].compareTo(arr2[((Obj)o).index]);
}
}
}
but if the array have X many items, then I will have to create X many Objs, is there another way that I could achieve this more simply? Another question is, if I do the above method what would be the time complexity for the sorting both in java and in JavaScript, are they all O(n^2)
? Thanks a lot
public class MyComparator implements Comparator<Integer> {
@Override
public int compare(Integer i1, Integer i2) {
return arr2[i1.intValue()].compareTo(arr2[i2.intValue()]);
}
}
Arrays.sort(arr1, new MyComparator());
This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.
这篇关于java的:排序ARRAY1基于数组2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!