使用Java排序器,即:
Collections.sort(myArrayList, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return x;
}
});
和
myArrayList.sort(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return x;
}
});
带有“ out”标签的标记表明该方法需要600-800毫秒才能完成。
当排序50-100个数组时,这只是一个很大的延迟。
我的问题是,创建自定义方法对数组进行排序会更快吗?
上面的代码效果很好,但是实现起来太慢了……
每个数组(myArrayList)约有44个元素。
完成1种排序需要600-800毫秒,因此50-100个阵列最多可能需要80000毫秒。
可执行文件:
System.out(timeMillis);
Collections.sort(fourtyFourItemsArrayL, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
Item i1 = o1 >= 16 ? player.getInventory().getItem(o1 - 16) : player.getEquipment().getItem(o1 - 1);
Item i2 = o2 >= 16 ? player.getInventory().getItem(o2 - 16) : player.getEquipment().getItem(o2 - 1);
int price1 = i1 == null ? 0 : i1.getDefinitions().getProtectionPrice();
int price2 = i2 == null ? 0 : i2.getDefinitions().getProtectionPrice();
if (price1 > price2)
return -1;
else if (price1 < price2)
return 1;
return 0;
}
});
System.out(timeMillis);
最佳答案
如果我没记错的话,那么Java Collections.sort()使用的排序算法的复杂度为O(n lg n)。
如果要构建比Collections.sort()更快的排序方法,则需要使用O(n)排序算法,例如Radix-Sort或Counting Sort。
如果您只约束数组中的50-100个元素,则我更喜欢使用Collections.sort()而不是编写大量仅用于对数字进行排序的代码。当n
如果要排序50-100个不同的数组,可以使用Java Threading。
关于java - Java集合排序与自定义排序-速度,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42174127/