0

This is my linear search code but I am getting an error with the array. I know what the error is and I have fixed it, but it still shows the same error:

Runtime Error: Runtime ErrorException in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at LinearSearchExample.linearSearch(LinearSearchExample.java:13) at LinearSearchExample.main(LinearSearchExample.java:40)

    public class LinearSearchExample
    {    
        public static int linearSearch(int[] arr, int key)
        {    
                for(int i=1;i<=arr.length;i++)
                    {    
                        if(arr[i] == key)
                            {    
                                return i;    
                            }    
                    }    
             return -1;    
         }  

    public static void main(String a[])
        { 
                int i, n, key, arr[],testcase;
                Scanner in = new Scanner(System.in);
                testcase = in.nextInt();
                System.out.println(testcase);

                for(i=0;i<testcase;i++)
                {
                        n = in.nextInt(); 
                        arr = new int[n];

                        for(i=0;i<n;i++){
                        arr[i] = in.nextInt();

                        }

                        key = in.nextInt();

                    System.out.println(linearSearch(arr, key)); 

                }   
        }    
}    
jkdev
  • 11,360
  • 15
  • 54
  • 77

1 Answers1

3

Java arrays are 0 based. Fix your loop in linearSearch()

for(int i=0;i<arr.length;i++)

Your second and third loops do this correctly :)

Steven Spungin
  • 27,002
  • 5
  • 88
  • 78
  • thanks it worked...just a small glitch i want to pass this code though 2 testcases....the code is returning answer for the 2nd testcase only where i am wrong? – Avada Kedavra Aug 12 '18 at 11:19