Search code examples
javaalgorithmbubble-sort

bubblesort won't fully compute


I have done this bubblesort algorithm but it doesn't fully sort the list. For example if I have the numbers 10,9,8,7,6 it will sort it as 9,8,7,6,10 and stop there. Now incase your wondering why I have put this condition in if (i + 1 < args.length) this is because I get an IndexOutOfBoundsException due to the index incrementing to 5 when making this comparison if (currentNumber > args[i + 1])

I have got rid of the extra code I did earlier since I overcomplicated the algorithm due to trying to get the whole list sorted which I got close to working out to the extent that the sorted list would get printed infinitely which was something I didn't want when I did it as a mutator method. In addition, some thought that the modifications I made there was not bubblesort even though the algorithm compared and swapped elements just like bubblesort. Therefore, this is why I decided to delete the extra code I worked on earlier.

My question is how do I get the whole list to be sorted? Since the algorithm so far doesn't do that.

package algorithm;

import java.util.Arrays;

public class Algorithm {

/**
 * @param args the command line arguments
 */
private static int list[] = {10, 9, 8, 7, 6};

public Algorithm() {
}

public static void main(String[] args) {

    Algorithm alg = new Algorithm();

    alg.bubblesort(list);

}

public int[] bubblesort(int[] args) {
    for (int i = 0; i < args.length; i++) {

        int currentNumber = args[i];
        if (i + 1 < args.length) {
            if (currentNumber > args[i + 1]) {
                args[i] = args[i + 1];
                args[i + 1] = currentNumber;
            }
        }

    }
    System.out.println(Arrays.toString(args));
    return args;
}
}

Solution

  • Bubble sort is done using two nested loops, you have only the inner loop that moves the greatest number to the last index of the array, you need to add the outer loop like this:

    for (int j = 0; j < args.length; j++) {
       for (int i = 0; i < args.length - j; i++) {
           int currentNumber = args[i];
           if (i + 1 < args.length) {
             if (currentNumber > args[i + 1]) {
                args[i] = args[i + 1];
                args[i + 1] = currentNumber;
             }
           }
       }
    }