Reputation: 1
Hello there I'm new to programming and I'm currently tasked to create a program relating to Sorting. and I keep getting the error
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at sorting.Sorting.main(Sorting.java:17)
Java Result: 1
The line it tells where the error is line 17 which contains:
if (ArrayOfInts[j] > ArrayOfInts[j + 1])
please help.. heres the whole thing.
public class Sorting{
public static void main(String[] args){
int[] ArrayOfInts = {42, 97, 3, 689, 14, 1076, 3000, 8, 632, 327, 976, 4215};
for(int i = ArrayOfInts.length; i >= 1; i--){
for(int j = 0; j < i; j--){
if (ArrayOfInts[j] > ArrayOfInts[j + 1]){
int temp = ArrayOfInts[j];
ArrayOfInts[j] = ArrayOfInts[j + 1];
ArrayOfInts[j - 1] = temp;
}
}
}
for(int i = 0; i < ArrayOfInts.length; i++){
System.out.println(ArrayOfInts[i] + " ");
}
}
}
Upvotes: 0
Views: 119
Reputation: 440
for(int i = ArrayOfInts.length; i >= 1; i--)
Hi please replace above code line with below line
for(int i = ArrayOfInts.length-1; i >= 0; i--)
Upvotes: 2
Reputation: 1403
I have made few correction to the code:
1. for 1st for loop, instead of int i = ArrayOfInts.length, use int i = ArrayOfInts.length-1, this is beacuse, length will return number of elements in array, and array is zero indexed hence in your case length will be 12 i.e. 0 to 11.
2.For 2nd for loop, instead of j- use j++ because j is starting from 0 to i.
3.instead of ArrayOfInts[j - 1] = temp; use ArrayOfInts[j + 1] = temp;
public static void main(String[] args)
{
int[] ArrayOfInts = {42, 97, 3, 689, 14, 1076, 3000, 8, 632, 327, 976, 4215};
for(int i = ArrayOfInts.length-1; i >= 1; i--)
{
for(int j = 0; j < i; j++)
{
if (ArrayOfInts[j] > ArrayOfInts[j + 1])
{
int temp = ArrayOfInts[j];
ArrayOfInts[j] = ArrayOfInts[j + 1];
ArrayOfInts[j + 1] = temp;
}
}
}
for(int i = 0; i < ArrayOfInts.length; i++)
{
System.out.print(ArrayOfInts[i] + " ");
System.out.println();
}
}
Upvotes: 0
Reputation: 19294
When j=0
, this line is problematic:
ArrayOfInts[j - 1] = temp;
as you try to access -1 index in an array.
Upvotes: 2