I have created a sample class which contains two integer array; one sorted and other unsorted. And I am printing contents of the array. Time taken to print sorted array is twice the time time required to print unsorted array.
Refer the code:
public class Demo {
public static void main(String[] args) {
int[] array1 = {1,2,3,4,5,6,7,8,9,10};
int[] array2 = {10,3,4,2,6,7,8,1,5,9};
long start = System.nanoTime();
for(int a:array1){
System.out.println(a);
}
System.out.println("Time required by sorted array\t"+(System.nanoTime() - start) / 1000000000.0);
start = System.nanoTime();
for(int a:array2){
System.out.println(a);
}
System.out.println("Time required by unsorted array\t"+(System.nanoTime() - start) / 1000000000.0);
}
}
Output:
1
2
3
4
5
6
7
8
9
10
Time required by sorted array 3.89505E-4
10
3
4
2
6
7
8
1
5
9
Time required by unsorted array 1.37727E-4
Why is there difference in time while displaying the numbers. Also I read somewhere that sorted array process faster, here the case is different.