Dinesh Sonachalam
Dinesh Sonachalam

Reputation: 1379

I'm performing an insertion sort and getting an array out of bounds exception in my while loop

Insertion Sort

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
class solution {
    public static void main(String[] args)
    {
        Scanner scan = new Scanner(System.in);
        int n = scan.nextInt();
        int[] a = new int[n];
        for (int i=0; i<n; i++)
        {
            a[i]=scan.nextInt();
        }
        for (int i=0; i<n; i++)
        {
            /*storing current element whose left side is checked for its
             correct position .*/
            int temp = a[i];
            int j=i;
            /* check whether the adjacent element in left side is greater or
            less than the current element. */
            while ((temp<a[j-1]) && (j>=0))
            {
                // moving the left side element to one position forward.
                a[j] = a[j-1];
                j = j-1;
                // moving current element to its  correct position.
                a[j] = temp;
            }
        }
        System.out.println("Sorted elements are:");
        for(int i=0;i<n;i++)
        {
            System.out.println(a[i]);
        }
    }
}

I do not understanding why my code throws this exception:

thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at solution.main(insertion.java:24)

in my while loop. Please guide me to solve this exception.

Upvotes: 4

Views: 278

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

for(int i=0;i<n;i++)

i starts from 0 so first time

i=0
j=i

and again first time a[j-1] will be a[(0 - 1)] = a[-1] here

 while((temp<a[j-1]) && (j>=0)) // array index starts from 0

hence exception

so it should be

while((j>0) && (temp<a[j-1]) )

This is the property of short-circuit(&&) operator, the next expression will only be evaluated if the previous was true.

Upvotes: 3

Related Questions