I am doing an insertion sort and getting an exception from the bounds in my while loop

Insert 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 understand why my code throws this exception:

stream "main" java.lang.ArrayIndexOutOfBoundsException: -1 on solution.main (insertion.java:24)

in my cycle while. Please help me resolve this exception.

+4
source share
1 answer
for(int i=0;i<n;i++)

i starts with 0, so for the first time

i=0
j=i

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

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

hence the exception

therefore he must be

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

(&), , .

+3

Source: https://habr.com/ru/post/1656893/


All Articles