I have an ArrayList with numbers from 10 MM to 20 MM
List<Long> l = new ArrayList<>();
for (long i = 10_000_000; i < 20_000_000; i++) {
l.add(i);
}
Why is the sum() function faster on a sorted array than on an unsorted?
public class Main {
public static void main(String[] args) {
List<Long> l = new ArrayList<>();
for (long i = 10_000_000; i < 20_000_000; i++) {
l.add(i);
}
System.out.println(sum(l));
Collections.shuffle(l);
System.out.println(sum(l));
Collections.sort(l);
System.out.println(sum(l));
}
static long sum(List<Long> l) {
long started = System.nanoTime();
long result = 0;
for (long v : l) {
result += v;
}
System.out.println(" duration: " + (System.nanoTime() - started) / 1_000_000 + "ms");
return result;
}
}
I execute the sum() function three times
- First time, on a sorted array
- Second time on unsorted
- And the third time again on sorted
On my computer, the execution time was
85ms
250ms
97ms
Why is the sum() function faster on a sorted array than on an unsorted?