Java Bubble Sort Returns Only Partially Sorted

• A+
Category：Languages

I'm new to Java, so have been trying to translate some old JS exercises into Java.

Here's a bubble sort (I know, I know...) that's not working:

class BubbleSort{ public static void main(String args[]){  int nums [] = {5, 4, 6, 3, 12, 1};   Boolean swap = true; while(swap){     swap = false;     for(int i = 1; i<nums.length ; i++){         if (nums[i - 1] > nums[i]){             int t = nums[i-1];             nums[i-1] = nums[i];             nums[i] = t;             swap = true;         }else{             swap = false;         }     } }  System.out.print("Sorted: "); for(int j=0 ; j<nums.length ; j++) System.out.print(nums[j] + " "); } }

It returns 4, 3, 5, 1, 6, 12... So a few swaps are taking place, but something is making it end early.

Can anyone spot my issue?

Just remove the else block in your code (as in the code sample below). You have to make another swap as soon as one thing is not ordered.

In your code, you only make another swap if the last items are in the wrong order. If the end of your array is ordered too soon, your sort ends too soon too.

class BubbleSort{     public static void main(String args[]){          int nums [] = {5, 4, 6, 3, 12, 1};          Boolean swap = true;         while(swap){             swap = false;             for(int i = 1; i<nums.length ; i++){                 if (nums[i - 1] > nums[i]){                     int t = nums[i-1];                     nums[i-1] = nums[i];                     nums[i] = t;                     swap = true;                 }/* else{                     swap = false;                 }*/             }         }          System.out.print("Sorted: ");         for(int j=0 ; j<nums.length ; j++)             System.out.print(nums[j] + " ");     } }