Search code examples
javabubble-sort

Java bubblesort 1-100


So I have most of the code completed. I just can't figure out why the sorted list is not in order from smallest to largest. The assignment was to generate 10 random integers from 1-10. Display the unsorted list. Display sorted (smallest to largest). Display arrays contents.

        int [] number = new int [10];

        System.out.print("Random Numbers:");
        for (int d = 0 ; d<number.length ; d++){
            int RandomG = g.nextInt(100) + 1;
            System.out.print("\t" + RandomG);
            number[d] = RandomG ;
        }
        System.out.print("\nSorted Numbers:"+Arrays.toString(BubbleSortAsceMethod(number)));
    }

    public static int [] BubbleSortAsceMethod(int[] x) {
        int temp;

        for (int i = 0; i < x.length; i++) {
            for (int j = 1; j < x.length -i; j++) {
                if (x[j - 1] < x[j]) {
                    temp = x[j - 1];
                    x[j - 1] = x[j];
                    x[j] = temp;
                }
            }
        }
        return x;   
    }
}

Solution

  • You need to change the condition

    current code

     if (x[j - 1] < x[j])
    

    Fixed code

    if (x[j - 1] > x[j])
    

    However you can enhance your code by adding isSorted flag.

    public static int[] BubbleSortAsceMethod(int[] x) {
        for (int i = 1; i < x.length; i++) {
            boolean isSorted = true;
    
            for (int j = 0; j < x.length - i; j++) {
                if (x[j] > x[j + 1]) {
                    int temp = x[j];
                    x[j] = x[j + 1];
                    x[j + 1] = temp;
                    isSorted = false;
                }
            }
            if (isSorted) {
                break;
            }
        }
        return x;
    }