Below is my code for Insertion Sort and i am facing an exception of array indexing.
import java.util.Scanner;
public class Insertion_Sort {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=4;
int ar[]=new int[n];
for(int i=0;i<n;i++)
{
ar[i]=sc.nextInt();
}
for(int i=1;i<n;i++)
{
int c=ar[i];
int j=i-1;
while(ar[j]>ar[j+1] && j>=0)
{
ar[j+1]=ar[j];
j--;
}
ar[j+1]=c;
}
for(int i=0;i<n;i++)
{
System.out.println(ar[i]);
}
}
}
This is the exception i am getting everytime i run this
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 4
at dfsd.Insertion_Sort.main(Insertion_Sort.java:17)