java:根据数组2对数组1进行排序
感谢 Zirak 在我的 上一篇文章我在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 );
在JavaScript中实现这一点的方法非常紧凑,Java实现也可以如此简单地实现吗?我只能想到实现 Comparable 接口,如下所示:
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]);
}
}
}
但是如果数组有 X 个项目,那么我将不得不创建 X 个 Objs,是否有另一种方法可以更简单地实现此目的?另一个问题是,如果我执行上述方法,在java和JavaScript中排序的时间复杂度是多少,它们都是O(n^2)
吗?多谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这相当于 JavaScript 排序。 Comparator 对象用作 JavaScript 中的回调函数。
This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.
尝试使用
TreeMap
(假设您想对整数进行排序),这意味着所有条目均按其字符串键排序:输出:
对数组进行排序并获取先前索引的新顺序您可以迭代数组并将索引作为 Integer 对象添加到映射中:
如果您需要按自然顺序以外的任何其他方式对键进行排序,您可以将
Comparator
添加到TreeMap
构造函数。Try using a
TreeMap<String, Integer>
(assuming you want to sort integers) which means all entries are sorted by their string key:Output:
To sort an array and get the new order of the previous indices you could iterate over the array and add the indices as Integer objects to the map:
If you need to sort the keys by anything else but the natural order, you can add a
Comparator<String>
to theTreeMap
constructor.回答你问题的第二部分:Java中的
Arrays.sort
保证了O(n log n)时间复杂度,如指定的API< /a>.In response to the second part of you question:
Arrays.sort
in Java has guaranteed O(n log n) time complexity, as specified in the API.