java - Array index out of bounds -
although tried solve exception using break
still fails on input "321". code bubble sort on hackerrank.
the error occurs on if(a[i+1]==n)
.
import java.io.*;`` import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class solution { public static void main(string[] args) { scanner in = new scanner(system.in); int n = in.nextint(); int[] = new int[n]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextint(); } // write code here int numswaps=0; for(int i=0;i<n;i++){ if(a[i+1]==n){ // error occurs here break; } else{ if(a[i]>a[i+1]){ int temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; numswaps++; } } } //firstelement=a[0]; //lastelement=a[n-1]; system.out.println("array sorted in"+" "+numswaps+" "+"swaps."+"\n"+"first element:"+" "+a[0]+"\n"+"last element:"+" "+a[n-1]); }
}
your condition i<n
overflow when i=n-1
, because adding i+1
, referencing array out-of-bounds.
the fix easy, however, change condition i<n-1
.
import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class solution { public static void main(string[] args) { scanner in = new scanner(system.in); int n = in.nextint(); int[] = new int[n]; for(int a_i=0; a_i < n; a_i++){ a[a_i] = in.nextint(); } // write code here int numswaps=0; for(int i=0;i<n-1;i++){ if(a[i+1]==n){ break; } else if(a[i]>a[i+1]){ int temp=a[i]; a[i]=a[i+1]; a[i+1]=temp; numswaps++; } } //firstelement=a[0]; //lastelement=a[n-1]; system.out.println("array sorted in"+" "+numswaps+" "+"swaps."+"\n"+"first element:"+" "+a[0]+"\n"+"last element:"+" "+a[n-1]); }
also, take bit of pride in code style; did couple touch-ups, far clean.
Comments
Post a Comment