0
public class JavaApplication28 {
   public static void main(String[] args) {
      int arr[]={5,4,3,2,1};
      int n=arr.length;
      int d=0;
      for(int i=1;i<n;i++){
          d=i;
          while(d>0 && arr[d-1]>arr[d]){
              d--; 
              int temp=arr[d-1];
              arr[d-1]=arr[d];
              arr[d]=temp;

          } 
      }
      for(int k=0;k<n;k++){
         System.out.println(arr[k]);
      } 
   } 
}   

It gives exception:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
    at javaapplication28.JavaApplication28.main(JavaApplication28.java:23)
C:\Users\ASUS™\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
currarpickt
  • 2,290
  • 4
  • 24
  • 39

2 Answers2

0

you can put d--; statement after swapping. If you perform before swapping. lookup tracing.

d=0

iteration 1: 

i=1, d=1(value of i)

In while(1(value of d)>0 && arr[0(d-1)]>arr[1]) condition true.

d--;(d having 0 value)

temp = arr[0-1] (access -1 element in arr)

But array bound start with 0 to array.length - 1.

Hardik
  • 1,519
  • 1
  • 10
  • 10
0

Your code contains

while(d>0 && arr[d-1]>arr[d]){
              d--; 
              int temp=arr[d-1];

Let's imagine that the value of d is 1. You will enter the while{} loop. Then you will subtract 1 from d which means d is now 0.

Then you try to get the array member at position 0-1 = -1. -1 is not a valid index since arrays start at 0 (zero).

David Brossard
  • 13,584
  • 6
  • 55
  • 88