Hi,
I implemented a solution to 439B where the most time consuming step was using Arrays.sort. On test case 29 it times out at 1000 ms if I sort using an int[]. However, I pass, and use at most 280 ms on test case 29 if I sort using an Integer[]. Can someone explain why java.util.Arrays.sort(), on Codeforces, is more than 3x faster when using Integer[] rather than int[] in this case? The size of the array is 100,000 and the integers inside the array are from 1 to 100,000.
Thanks
My code is here:
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt(); // number of subjects
long x = sc.nextLong(); // initial per-chapter learning power of a subject
Integer[] cps = new Integer[n]; // number of chapters per subject
for (int i = 0; i < n; ++i) {
cps[i] = sc.nextInt();
}
Arrays.sort(cps); // Times out when cps is an int[]. Must be Integer[].
long totalTime = 0;
for (int i = 0; i < n; ++i) {
totalTime += cps[i] * x;
if (x != 1) {
--x;
}
}
System.out.println(totalTime);
}
}
That is because there is anti quick-sort test case and Java uses quick-sort for primitives
Java uses merge-sort for Object arrays and quick-sort for primitive arrays.
For merge-sort time complexity is O(n*logn) for all cases but an anti quick-sort input's time complexity may be O(n*n) and will result in TLE.
This is 17months already and I learnt this the hard way.
In the second problem of the Educational Round that just passed, Many Java solutions did not pass. It turns out there was an anti quick sort test case number 20.
My solution passed the moment i used Object Integer. :)
ANTI-QUICK SORT TEST CASE