Why Arrays.sort(Integer) is more fast that Arrays.sort(int) ?(JAVA)
# | User | Rating |
---|---|---|
1 | tourist | 3985 |
2 | jiangly | 3814 |
3 | jqdai0815 | 3682 |
4 | Benq | 3529 |
5 | orzdevinwang | 3526 |
6 | ksun48 | 3517 |
7 | Radewoosh | 3410 |
8 | hos.lyric | 3399 |
9 | ecnerwala | 3392 |
9 | Um_nik | 3392 |
# | User | Contrib. |
---|---|---|
1 | cry | 169 |
2 | maomao90 | 162 |
2 | Um_nik | 162 |
4 | atcoder_official | 161 |
5 | djm03178 | 158 |
6 | -is-this-fft- | 157 |
7 | adamant | 155 |
8 | Dominater069 | 154 |
8 | awoo | 154 |
10 | luogu_official | 150 |
Why Arrays.sort(Integer) is more fast that Arrays.sort(int) ?(JAVA)
Name |
---|
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)