Why Arrays.sort(Integer) is more fast that Arrays.sort(int) ?(JAVA)
№ | Пользователь | Рейтинг |
---|---|---|
1 | tourist | 4009 |
2 | jiangly | 3823 |
3 | Benq | 3738 |
4 | Radewoosh | 3633 |
5 | jqdai0815 | 3620 |
6 | orzdevinwang | 3529 |
7 | ecnerwala | 3446 |
8 | Um_nik | 3396 |
9 | ksun48 | 3390 |
10 | gamegame | 3386 |
Страны | Города | Организации | Всё → |
№ | Пользователь | Вклад |
---|---|---|
1 | cry | 167 |
2 | Um_nik | 163 |
3 | maomao90 | 162 |
3 | atcoder_official | 162 |
5 | adamant | 159 |
6 | -is-this-fft- | 158 |
7 | awoo | 157 |
8 | TheScrasse | 154 |
9 | Dominater069 | 153 |
9 | nor | 153 |
Why Arrays.sort(Integer) is more fast that Arrays.sort(int) ?(JAVA)
Название |
---|
Because of antiquicksort tests. You can random-shuffle your array before sorting and everything will be fine
As I can do random-shuffle, could you tell me more about what it means to do that. Because as I understand it has to do with the algorithms using JAVA to order according to data type.
Let's say that you are given a random permutation of
int
s from 1, 2, ..., n. If you sort them withArrays.sort
then you are almost completely sure that it will be , that means that the probability of hitting a permutation that causes O(n2) is so low that is negligible. Furthermore, it will be faster than using a Mergesort (because Quicksort is almost always faster than Mergesort).However, if the input is not a random permutation, then whoever made that input could have been "malicious" and tuned the order of the numbers in order to cause O(n2) behavior. If you use random shuffle, then you're back in the case no matter what original order the input had.
See dalex's post if you want to see how to generate a "malicious" input.
The main reason is that Java uses two different sorting algorithms in the cases you mentioned.
In the
Arrays.sort(int)
(or other primitive types) case, Java uses Quicksort, which has a O(n2) worst case. Instead, in theArrays.sort(Object)
case, it uses Mergesort, which has a worst case.Why? Check out the answer here.
on average sample, sort(int) is much faster (because it works with primitives), but it has O(N^2) worstcase because it's plain quicksort, and in certain CF problems other users might use it to hack solution. sort(Integer) is mergesort and while it's slower, its worstcase is still O(N*log N)