Question

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!

Was it helpful?

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.

OTHER TIPS

From what I see, the swapping works ok. Your problem is, that the inner part of the while cycle will never repeat more than once, because of the way you set Done to true at the end. This way, only the position of the smallest element in the array is determined correctly.

If you want it to perform full bubble sort, I'd suggest exchanging the outer while cycle for a for cycle, like this

for (int y = 0; y < Bub.length - 1; y++) {
    for (int x = 0; x < Bub.length - 1; x++) {
        // do stuff
    }
}

or if you want to keep the while cycle, you should set up the ending condition correctly, as in

if ( *everything is sorted* ) {
    Done = true;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top