class Bubble {
public static void main(String args[]) {
int[] a={20, 22, 19, 45, 9};
int temp;
for (int i = 0; i <= a.length - 1; i++) {
for (int j = 0; j <= a.length - 1; j++) {
if (a[j] > a[j + 1]) {
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.println(a[i] + "");
}
}
}
this Bubble sort program gives me "array out of bound exception" can sombody help me to resolve this
Asked
Active
Viewed 39 times
-2
-
This is the time to start the debugger. – f1sh Jul 30 '20 at 14:57
-
You're not being charged by the character in your code. People are more likely to be able to help you with your code if they can read it. – khelwood Jul 30 '20 at 14:58
-
you're trying to get something out of an array, which is beyond the array. For example; you have an array that can hold 8 items and you're trying to get the 9th item. It probably has something to do with your for loop and the a[j+1] – Arnoud Jul 30 '20 at 15:04
-
2Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Scratte Jul 30 '20 at 15:13
-
This program tries to access two elements outside the array. – NomadMaker Jul 30 '20 at 16:55
1 Answers
0
Please format your code correctly next time. It'll make it much easier to help you.
Your main problem is that in the nested loop that iterates over j
, you compare a[j]
with a[j+1]
. Since the maximum range for j
is 4
(size of array is 5
), at the last index you won't be able to compare a[4]
with a[5]
because a[5]
does not exist. This is what gives the exception.
To fix this, you should make j iterate as such:
int j=0; j < a.length-2; j++
You don't have to process the last index since it does not have anything subsequent to be compared to.

Maurice Kasomwung
- 178
- 1
- 12