Bubble Sort

Author: Tatyana Milkina

1. What Is Bubble Sort in Java?

Let’s explore one of the most famous teaching algorithms — bubble sort. While not efficient for large datasets, it's ideal for understanding how sorting algorithms work.

Bubble sort idea: During each pass, adjacent elements are compared. If they’re in the wrong order, they are swapped. The largest elements "bubble" down to the end of the array.

Visualizing the array top-down, we start at index 0 and move downward toward the end of the array.

Bubble sort first pass

After the first pass, the smallest element "floats" to the top — hence the name bubble sort. We repeat the process, excluding already sorted elements. On each pass, the next smallest item is placed in its correct position.

All passes of bubble sort

2. Bubble Sort Algorithm in Java

Let’s implement bubble sort in Java. The outer for loop tracks each pass, and the inner loop compares and swaps adjacent elements using a temporary variable tmp.

In this version, we iterate backward from the end of the array toward index i, shrinking the comparison range with each pass:

public class BubbleSorter {
    public static void sort(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            for (int j = array.length - 1; j > i; j--) {
                if (array[j - 1] > array[j]) {
                    int tmp = array[j - 1];
                    array[j - 1] = array[j];
                    array[j] = tmp;
                }
            }
        }
    }
}
Курс 'Java для начинающих' на Udemy Курс 'Java для начинающих' на Udemy
Read also:
Comments