424,287 Members | 2,113 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,287 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++)
while(k<arr[j] && (j>=0))
arr[j+1]= arr[j];
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};


Feb 9 '18 #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.
Expand|Select|Wrap|Line Numbers
  1. while(j>=0 %% k<arr[j])
would not crash!
Feb 12 '18 #2

Post your reply

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