11th August, 2017

Bubble sort in Java

A bubble sort algorithm in Java

This is a follow-up to my previous Bubble sort in Python post where I briefly outlined the bubble sort algorithm and wrote an implementation using the Python programming language.

The speed tests in my previous bubble sort post are pretty appalling - and this is mostly because bubble sort is a hideously slow and inefficient method of sorting numbers. However, another factor affecting these speeds is the Python interpreter itself; Python is an interpreted language and it therefore inherently slow compared to languages that are compiled down to byte code or machine code. It is for this reason I decided to re-create bubble sort in Java - to compare speeds and to introduce myself to the language.

Speed tests

I have tested this bubble sort algorithm to time how long it takes to sort 100, 1000, and 10,000 unsorted random numbers between 0 and 1000.
Each test was run 3 times (to find the average) using a 2016 MacBook air with a 1.6GHz CPU and 4GB of RAM.
All results are recorded in milliseconds, and averages are rounded to 1 decimal place.

100 elements:
    test 1: 0ms
    test 2: 1ms
    test 3: 1ms
    average: 0.7ms
1,000 elements:
    test 1: 15ms
    test 2: 13ms
    test 3: 15ms
    average: 14.3ms
10,000 elements:
    test 1: 345ms
    test 2: 388ms
    test 3: 399ms
    average: 377.3ms

So Python took almost a full minute to sort 10,000 elements, while Java took a mere 377 milliseconds.

Source code

private static int[] bubbleSort(int[] values) {
    boolean isSorted = false;
    while (!isSorted) {
        isSorted = true;
        for (int i = 0; i < values.length - 1; i++) {
            if (values[i] > values[i + 1]) {
                values[i] = values[i] ^ values[i + 1];
                values[i + 1] = values[i] ^ values[i + 1];
                values[i] = values[i] ^ values[i + 1];
                isSorted = false;
    return values;

Thank you for reading.


Leave a comment

Invalid or missing field(s).
Comment sent successfully, please wait for it to be approved.

This post has no comments