Bubble sort in Java

Simple Java implementation of the Bubble sort algorithm.


For simple usage, we will use an array of integers.

Random array generation

Before testing any sorting algorithms, we need a random array. So, let’s generate it:
1. Generate sorted array from 1 to N
2. Shuffle it by exchanging each item with the randomly selected item.

private static int[] generateRandomArray(int length) {
    int[] result = new int[length];
    for (int i = 0; i < length; i++) {
        result[i] = i + 1;
    }
    shuffle(result);
    return result;
}

private static void shuffle(int[] array) {
    if (array.length > 1) {
        Random random = new Random();
        for (int i = 0; i < array.length; i++) {
            swap(array, i, random.nextInt(array.length));
        }
    }
}

private static void swap(int[] array, int i, int j) {
    int temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

Bubble Sort Java implementation

private static void bubbleSort(int[] array) {
    boolean swapped;
    do {
        swapped = false;
        for (int i = 1; i < array.length; i++) {
            if (array[i - 1] > array[i]) {
                swap(array, i - 1, i);
                swapped = true;
            }
        }
    } while (swapped);
}

Bubble Sort Java example

This example does:
1) array generation;
2) print the array;
3) sort array with Bubble sort;
4) print the result.

Full Java code of the example:

import java.util.Arrays;
import java.util.Random;

/**
 * @author Denis Migol
 */
public class BubbleSort {
    private static int[] generateRandomArray(int length) {
        int[] result = new int[length];
        for (int i = 0; i < length; i++) {
            result[i] = i + 1;
        }
        shuffle(result);
        return result;
    }

    private static void shuffle(int[] array) {
        if (array.length > 1) {
            Random random = new Random();
            for (int i = 0; i < array.length; i++) {
                swap(array, i, random.nextInt(array.length));
            }
        }
    }

    private static void swap(int[] array, int i, int j) {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    private static void bubbleSort(int[] array) {
        boolean swapped;
        do {
            swapped = false;
            for (int i = 1; i < array.length; i++) {
                if (array[i - 1] > array[i]) {
                    swap(array, i - 1, i);
                    swapped = true;
                }
            }
        } while (swapped);
    }

    public static void main(String[] args) {
        int[] array = generateRandomArray(10);
        System.out.println(Arrays.toString(array));

        bubbleSort(array);
        System.out.println(Arrays.toString(array));
    }
}

Output

[8, 4, 9, 7, 2, 5, 10, 1, 3, 6]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]