Java Bubble Sort Example

This Java source code example demonstrates the usage of the bubble sort algorithm in Java programming language.

Java Bubble Sort Example

Sorting an array of integers using the bubble sort algorithm:
import java.util.Arrays;

// Sorting an array of integers using bubble sort algorithm
public class BubbleSortExample {

    public static void main(String[] args) {

        int nums[] = {
            3,
            7,
            1,
            15,
            12,
            6,
            11,
            9
        };

        doBubbleSort(nums);

        System.out.println(Arrays.toString(nums));
    }

    private static void doBubbleSort(int a[]) {

        int len = a.length;

        for (int i = 0; i < len - 1; i++) {
            for (int j = 0; j < len - i - 1; j++) {

                if (a[j] > a[j + 1]) {

                    // swap elements
                    int temp = a[j];
                    a[j] = a[j + 1];
                    a[j + 1] = temp;
                }
            }
        }
    }
}

Output

[1, 3, 6, 7, 9, 11, 12, 15]


Comments