Search code examples
javasortingswapbubble-sort

Bubble sort swaps every number regardless of value


import java.util.*;
public class Zhangbubble
{
    public static void main (String[] args)
    {
        int Bub[] = new int[6];
        Random randy = new Random();
        boolean Done = false;
        for (int x=0; x<6; x++)
        {
            Bub[x] = randy.nextInt(100);
            System.out.println (Bub[x]);
        }
        System.out.println ("This is the original array");
        while (! Done)
        {
            Done = true;
            for(int x = 0; x < Bub.length - 1; x++) 
            {
                if(Bub[x+1] < Bub[x]) 
                {
                    int temp = Bub[x];
                    Bub[x] = Bub[x+1];
                    Bub[x+1] = temp;
                    System.out.println ("Number "+Bub[x]+ " and  " +Bub[x+1]+ " have     been switched");
                }
            }
            for(int x = 0; x < Bub.length; x++) 
            {
                System.out.println(Bub[x]);

            }
            Done = true;
        } 

    }
}

My bubble sort works in ascending order but it only sorts once. It seems to be working fine but I can't pinpoint what's making it not loop. It will run through the number sequence once but it won't keep sorting after the first initial check. Can someone help me to make it loop until the entire sequence is in order? Alright I think I may have figured it out. I got rid of Done = true and instead added Done = false right after the sorting algorithm. It seems to be working great now but if anyone spots something wrong please don't hesitate to point it out!


Solution

  • It doesn't swap "everything". However, if you are trying to sort the array in the ascending order, the if condition is the wrong way round.

    Additionally, you need to carefully think about when you should be setting Done to true. The current approach is flawed.