public class BubbleSorter { public static void sort (int[] arr) { for (int i = 0; i < arr.length; i++) { for (int j = 0; j < arr.length ; j++) { if (arr[j] > arr[j + 1]) { int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t; } } } } } 
  • You know, they usually compare arr [i] with arr [j] ... - Peter Slusar

3 answers 3

In the condition of the second cycle, change for (int j = 0; j < arr.length; j++) to for (int j = 0; j < arr.length - 1; j++) . Because when j <arr.length goes beyond the array.

    The error is that when you access j + 1 element of the arr array, you go beyond it.

    Suppose, for example, arr.length == 10 , then for j = 9 you will try to refer to the element arr[9 + 1] = arr[10] , but the last element of the array arr is arr[9] .

      ArrayIndexOutOfBoundsException occurs due to going beyond the array, you have in the second loop, where at the last iteration arr[j + 1] is arr[arr.lenght] , that is, an error, went beyond the limit of arr .

      Modify nested loop

      for (int j = 0; j < arr.length ; j++)

      on that

      for (int j = 0; j < arr.length - i - 1 ; j++)


      1. Solved the problem of going beyond the array, now at the last iteration
        arr[j + 1] will be arr[arr.lenght - 1]

      2. We do not make unnecessary checks with already sorted elements (for each new i, the array to be sorted is less than 1)