Search code examples
javabubble-sort

BubbleSort Algorithm Returning Undesired Results


Here is my implementation of the bubble sort algorithm.

 import java.util.Arrays;

 public class BubbleSort {
    public static void main(String[] args) {
        int[] unsorted = {1,3,5,6,2};
        System.out.println(Arrays.toString(unsorted));
        bubbleSort(unsorted);
        System.out.println(Arrays.toString(unsorted));
    }

    public static void bubbleSort(int[] unsorted){
        int i;
        int j;
        int temp;
        for (i = 0; i < unsorted.length; i++) {
            for (j = 1; j < unsorted.length-1; j++) {
                if (unsorted[i] > unsorted[j]) {
                    temp = unsorted[i];
                    unsorted[i] = unsorted[j];
                   unsorted[j] = temp;
                 }
             }
        }
   }
 }

Here is the output:

[1, 3, 5, 6, 2]
[1, 6, 5, 3, 2]

This is clearly wrong, but my logic seems alright.


Solution

  • Both of your problems are with this line:

    for (j = 1; j < unsorted.length-1; j++) {
    

    You don't want to loop from the first element, you want to loop from the first element after i:

    for (j = i+1; j < unsorted.length-1; j++) {
    

    You also need to go all the way to the end:

    for (j = i+1; j < unsorted.length; j++) {