So I have to write a program in java that has to search for an object(String) in an array forwards and backwards and see which one is faster. When I am testing, it takes a lot longer going forward for the program to find an object at the beginning of the array then going backwards. I am confused as it should be faster since it is at the beginning of the array. Can someone explain to me what I am doing wrong?
import java.util.Scanner;
import java.util.Arrays;
public class LinearStringSearch{
public static long startTime;
public static long endTime;
public static long startTimeB;
public static long endTimeB;
public static void printArray(String arr[]){
for(int i = 0; i < arr.length; i++){
System.out.println(arr[i]);
}
}
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.println("Please enter a word and we will check our database for it");
String a = input.nextLine();
String [] words = new String[10];
for (int i = 0; i < words.length; i++){
words[i] = "Test " + (i + 1);
}
long startTime = System.nanoTime();
for(int i = 0; i < words.length; i++){
if (a.equals(words[i])){
System.out.println("It is located at index: " + i);
break;
}
}
long elaspedTime = System.nanoTime() - startTime;
System.out.println("Going from the front, it took " + elaspedTime);
long startTimeBack = System.nanoTime();
for (int i = words.length-1; i >= 0; i--){
if (a.equals(words[i])){
System.out.println("It is located at index: " + i);
break;
}
}
long elapsedTimeB = System.nanoTime() - startTimeBack;
System.out.println("Going from the back, it took " + elapsedTimeB);
}
}