Java bubble sort

Issue

i’m trying to create a bubble sort but I there is something wrong with my code. The output is : 82345679. I would like it to be : 23456789.

package com.company;

public class Main {

    public static void main(String[] args) {
        // write your code here

        int[] tab  {9,8,7,6,5,4,3,2};
        int[] result  {9,8,7,6,5,4,3,2};

        for (int i  0; i < result.length; i++ ) {
            if (i < result.length - 1 ) {
                if (result[i] > result[i+1]) {
                    result  permute(result, i);
                    i  0;
                }
            }
        }

        for (int i: result) {
            System.out.print(i);
        }

    }

    public static int[] permute (int[] tableau, int index) {
        int temp;
        temp  tableau[index];
        tableau[index]  tableau[index+1];
        tableau[index+1]  temp;
        return tableau;
    }
}

Solution

The issue is with the combination of i 0 and i++ in the for loop. Whenever you go in the i 0 branch, you end up restarting at 1 because of the i++. Resulting in always skipping the 8 after the first iteration where the 9 is moved to the end.

So, either restart at -1, or use a while loop and only increment in an else block. For example:

int i  0;
while (i < result.length - 1) {
    if (result[i] > result[i+1]) {
        permute(result, i)
        i  0;
    } else {
        i++;
    }
}

However, I would advise against the one-loop bubble sort, because the algorithm complexity is harder to see (it is still O(n^2), but with only one loop it can give the impression that it is O(n)).

Answered By – njzk2

Leave a Comment