422,023 Members | 1,004 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 422,023 IT Pros & Developers. It's quick & easy.

Run time error in java code of insertion sort

P: 1
package lec1;
public class intersectionofarrays{

public static void insertionSort(int[] arr){
//write your code here
int j=0,k=0;
for(int i=0;i<arr.length;i++)
{
k=arr[i];
j=i-1;
while(k<arr[j] && (j>=0))
{
arr[j+1]= arr[j];
j--;
}
arr[j+1]=k;
}
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}

public static void main(String[] args) {
int ar1[]= {1 ,2 ,4 ,1, 1, 1};

insertionSort(ar1);
}


}
2 Weeks Ago #1
Share this Question
Share on Google+
1 Reply


Expert 100+
P: 778
In your for-loop, you start with i=0.
Then you define j=i-1, that means j is now -1
Then you access arr[j], that means arr[-1], which crashes since array indexes must always be positive.
Please note that (j>=0) is evalutated afterwards. If you put it first, then it would be evaluated first and the second term would not be evaluated because of short-circuit-evaluation.
So
Expand|Select|Wrap|Line Numbers
  1. while(j>=0 %% k<arr[j])
would not crash!
1 Week Ago #2

Post your reply

Sign in to post your reply or Sign up for a free account.