11th August, 2017

Selection sort in Java

A selection sort algorithm in Java.

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

Selection sort is much faster compared to bubble sort; I decided to recreate the algorithm in Java to take advantage of the language's superior speed / performance compared to Python.

Speed tests

I have tested this selection 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: 0ms
    test 3: 0ms
    average: 0ms
1,000 elements:
    test 1: 9ms
    test 2: 8ms
    test 3: 9ms
    average: 8.7ms
10,000 elements:
    test 1: 84ms
    test 2: 91ms
    test 3: 81ms
    average: 85.3ms

So Python took, on average, 9,964.3 milliseconds to sort 10,000 elements, while Java took, on average, a mere 85.3 milliseconds.

Source code

private static int[] selectionSort(int[] values) {
    int offset = 0;
    while (offset < values.length) {
        int smallest = offset;
        for (int i = offset; i < values.length; i++) {
            if (values[i] < values[smallest]) {
                smallest = i;
        values[offset] = values[offset] ^ values[smallest];
        values[smallest] = values[offset] ^ values[smallest];
        values[offset] = values[offset] ^ values[smallest];
        offset += 1;
    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