HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaMinor

A simple bubble sort implementation in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
simpleimplementationjavabubblesort

Problem

I've written a Bubble Sort algorithm in Java and I want a review on these:

  • Performance improvements.



  • Code conventions.



  • Algorithm design improvements.



  • Cleaner approaches.



I would highly appreciate if you can review based on the points above, and I would prefer if you can add more points on top if it if you find necessary.

Here's the code:

package com.hassanalthaf.sortingalgorithms;

public class BubbleSort {

    private int temporary;

    public int[] sort(int[] numbers) {
        for (int mainIterations = 0; mainIterations  numbers[comparisons + 1]) {
                    this.temporary = numbers[comparisons];
                    numbers[comparisons] = numbers[comparisons + 1];
                    numbers[comparisons + 1] = this.temporary;
                }
            }
        }

        return numbers;
    }

}


Here's my main class calling the BubbleSort sort method:

package com.hassanalthaf.sortingalgorithms;

public class Main {

    public static void main(String[] args) {
        int[] numbers = {1, 20, 51, 12, 43, 2, 20};

        BubbleSort bubbleSort = new BubbleSort();

        numbers = bubbleSort.sort(numbers);

        for (int iterations = 0; iterations < numbers.length; iterations++) {
            System.out.println(numbers[iterations]);
        }
    }

}


This produces an output:

1
2
12
20
20
43
51

Solution

Bug

On the array { 3, 1, 4, 5, 2 }, the result will be { 3, 1, 2, 4, 5 }. In order to fix this, in the inner for loop change

int comparisons = 1;


to

int comparisons = 0;


API

The Java coding conventions dictate that sorting routines are declared static, return nothing (have type void), and provide the version of the routine that can sort a particular subarray within an array.

Also, you might prefer to declare the constructor of BubbleSort as private, since that object does not do anything of interesting on its own.

Algorithm

Your algorithm runs always in \$\Theta(N^2)\$, whereas the actual bubble sort runs in \$\Theta(N)\$ on almost sorted input. Refer to the Wikipedia for pseudocode that is more adaptive.

Printing an integer array

Instead of

for (int iterations = 0; iterations < numbers.length; iterations++) {
    System.out.println(numbers[iterations]);
}


you can easily write

System.out.println(Arrays.toString(yourArray));


Hope that helps.

Code Snippets

int comparisons = 1;
int comparisons = 0;
for (int iterations = 0; iterations < numbers.length; iterations++) {
    System.out.println(numbers[iterations]);
}
System.out.println(Arrays.toString(yourArray));

Context

StackExchange Code Review Q#133012, answer score: 2

Revisions (0)

No revisions yet.