gpt4 book ai didi

Java集合排序和自定义排序-速度

转载 作者:行者123 更新时间:2023-12-01 20:57:06 34 4
gpt4 key购买 nike

使用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-SortCounting Sort .

如果您的数组中只有 50-100 个元素,我更喜欢使用 Collections.sort() 而不是编写大量代码来仅对数字进行排序。当 n <= 100 时,O(n lg n) 与 O(n) 之间没有太大区别。

如果你想对 50-100 个不同的数组进行排序,你可以使用 Java Threading

关于Java集合排序和自定义排序-速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42174127/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com