One of the problems mentioned by someone was that you use different indexes for each algorithm. So, to fix this, I reworked your code a bit. Here is the code I have:
int[] arr = new int[1000]; Random r = new Random(); for(int i = 0; i < arr.length; i++){ arr[i] = r.nextInt(); } int N = 1000000; List<Integer> indices = new ArrayList<Integer>(); for(int i = 0; i < N; i++){ //indices.add((int) Math.floor(Math.random()*arr.length/2)*2); //even only indices.add((int) Math.floor(Math.random()*arr.length/2)*2+1); //odd only //indices.add((int) Math.floor(Math.random()*arr.length)); //normal } long startTime = System.nanoTime(); for(Integer i : indices) { search(arr, arr[i]); } System.out.println("Average Time: "+(System.nanoTime()-startTime)/(float)N+"ns"); startTime = System.nanoTime(); for(Integer i : indices) { skipSearch(arr, arr[i]); } System.out.println("Average Skip Search Time: "+(System.nanoTime()-startTime)/(float)N+"ns");
So, you will notice that I made an ArrayList<Integer> to store the indices, and I provide three different ways to populate this list of arrays - one with even numbers, one with odd numbers and your original random method.
Running with even numbers only causes this output:
Average time: 175.609ns
Average search time: 100.64691ns
Running with odd numbers only causes this output:
Average time: 178.05182ns
Average search time: 263.82928ns
Running with the original random value produces this output:
Average time: 175.95944ns
Average search time: 181.20367ns
Each of these results makes sense.
If you select only indices, your skipSearch algorithm is set to O (n / 2), so we process no more than half of the indices. Usually we don’t need constant factors in time complexity, but if we really look at runtime, then it matters. In this case, we literally halve the problem, so this will affect the execution time. And we see that the real runtime is almost cut in half, respectively.
When choosing only odd indices, we see a much greater effect on runtime. This is to be expected because we process at least half of the indexes.
When using the original random selection, we see that skipSearch does worse (as we expect). This is due to the fact that on average we will have an even number of even indices and odd indices. Even numbers will be found quickly, but odd numbers will be found very slowly. A linear search will find index 3 at the beginning, while skipSearch processes approximately O (n / 2) elements before it finds index 3.
As for why your source code gives odd results, as far as I can tell in the air. Maybe the pseudo-random number generator slightly supports even numbers, this may be due to optimization, this may be due to the madness of branch prediction. But this, of course, was not a comparison of apples with apples, choosing random indices for both algorithms. Some of these things can still affect my results, but at least two algorithms are trying to find the same numbers.