Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 361
  • Last Modified:

how to do a buble sort animation using java?

for(int x = 0; x < array.length - 1; x++){
    for(int y = 0; y < array.length - 2; y ++){
         if(array[y] > array[y+1]){
            swap(array, y, y+1);
         }
         repaint(); // ask to repaint the component
     }
}

if code is on above, but i can't get the result i expect. then repaint() paint the sorted array.
my expected result is to paint the array that is not sorted yet.
how!? help!!
0
tttntt
Asked:
tttntt
2 Solutions
 
Mayank SAssociate Director - Product EngineeringCommented:
That is definitely not the loop for bubble-sort, and I still don't understand your question properly. Do you want to first display the unsorted array, then sort it, and then display the sorted array again?

Mayank.
0
 
funnyveryfunnyCommented:
Hi,

You'll find in yr code that the last element is not sorted, the correct code is below:

for(int x = 0; x < array.length; x++){
   for(int y = 0; y < array.length - 1; y ++){
        if(array[y] > array[y+1]){
           swap(array, y, y+1);
        }
    }
}

So you want to illustrate the bubble-sort. First of all by default repaint() calls paint(), which itself is an empty method, that means you have to provide drawing instructions.

Now I'm not sure of what type of animation you're trying to achieve. Assuming you're aiming for an animation of bubble-sort in action, one way is as follow:

1) Create an array of buttons that has the same length as yr data.
2) Let the name each of button corresponds to each of the data item. In effect you have a row of buttons display on the screen.
3) Run yr bubble sort, at each swap change the names of buttons that are involved then repaint().
3) Add Thread.sleep() to slow down the animation.

So hopefully what you'll see on screen are items changing positions (bubbling).

I always thought about writing one myself but never got round to do it. So it would be nice to see this implemented, even better if you could extend the animation for dramatic effects (license to entertain). Also, there is no animated pointer it'd be nice if you could provide one.

Let me know if you need further help.

Bye - I know this is all writing and no sample-coding, but again I suspect you want to do this yrself.

0
 
Mayank SAssociate Director - Product EngineeringCommented:
Funnyveryfunny,

is your bubble-sort correct too?

I would write the standard bubble-sort as:

for ( int x = 1 ; x < array.length ; x ++ )
  for ( int y = 0 ; y < array.length - x ; y ++ ) // please notice: array.length - X
    if ( array[y] > array[y+1] )
           swap ( array, y, y + 1 ) ; // end if, for


Mayank.

0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
funnyveryfunnyCommented:
Hi mayankeagle,

My code is correct but not efficient like yrs, given the time complexity of bubble sort is O(n^2). So logically I thought it would go something like that.

You're right.

Anyway, I just wrote a little code for the animation here using your version. How creative are you???

public class BubbleSortAnimation extends Frame{
  int[] data;
  Button[] b_data;
  final int MAX =10;
  Panel p;
  Label l;

  public BubbleSortAnimation() {
    data = new int[MAX];
    b_data = new Button[MAX];
    p = new Panel(new FlowLayout());
    Random r = new Random();
    int temp;
    for(int i=0;i<MAX;i++){
      temp = r.nextInt(100);
      data[i]=temp;
      b_data[i] = new Button(Integer.toString(temp));
      b_data[i].setEnabled(false);
      b_data[i].setBackground(Color.white);
      p.add(b_data[i]);
    }
    l = new Label();
    this.add("Center",p);
    this.add("South",l);
    this.setSize(600,100);
    this.setVisible(true);
  }

  public void bubbleSort() throws Exception{
    l.setText("Sorting....");
    repaint();
    for(int i=1;i<MAX;i++)
      for(int j=0;j<MAX-i;j++){
         b_data[j].setBackground(Color.green);
         b_data[j+1].setBackground(Color.yellow);
         repaint();
         Thread.sleep(500);
         if(data[j]>data[j+1]){
           int temp = data[j];
           data[j] = data[j+1];
           data[j+1] = temp;
           b_data[j].setBackground(Color.yellow);
           b_data[j].setLabel(Integer.toString(data[j]));
           b_data[j+1].setBackground(Color.green);
           b_data[j+1].setLabel(Integer.toString(data[j+1]));
           repaint();
           Thread.sleep(500);
         }
         b_data[j].setBackground(Color.white);
         b_data[j+1].setBackground(Color.white);
         Thread.sleep(500);
      }
    l.setText("Sorted!!!");
    repaint();
  }

  public static void main(String[] args) {
    BubbleSortAnimation b = new BubbleSortAnimation();
    try{
      b.bubbleSort();
    }
    catch(Exception e){
      System.out.println(e);
    }
  }
}

Bye.
0
 
mlmccCommented:
His code is correct.  Remember C arrays index from 0 to Length-1  So Arr[6] has indexes 0, 1, 2 , 3 , 4 , 5

The code provided by funnyveryfunny and mayankeagle will step outside the array boundaries when y = length-1

mlmcc
0
 
funnyveryfunnyCommented:
To mlmcc,

>>>"The code provided by funnyveryfunny and mayankeagle will step outside the array boundaries when y = length-1"

First of all your statement is correct in its respect but I think you're confused here, y only reaches y = length-2 so it'll never step outside the upper-boundary. To support yr statement the code will now have to be like this:

for(int x = 0; x <= array.length - 1; x++){
   for(int y = 0; y <= array.length - 2; y ++){
        if(array[y] > array[y+1]){
           swap(array, y, y+1);
        }
    }
}

Otherwise the last element will never be sorted unless yr assuming item[y]<=item[length-1] for all y=0..length-2.

fvf.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
mlmcc ,

>> The code provided by funnyveryfunny and mayankeagle will step outside the array boundaries when y = length-1

Oh ya??

WELL, 'y' WILL NEVER BE 'LENGTH - 1' IF YOU FOLLOW MY CODE,

because 'x' starts from 1 in my loop and goes till n - 1 (n-2 iterations for the outer loop - standard bubble-sort), and so, the maximum value of 'y' ( y < array.length - x ) will be when 'x' is 1, i.e., 'array.length - 2', meaning that (y + 1) in the 'if' statement will be array.length - 1, and so, both, 'y' and 'y + 1' will be within the array's bounds!

Please verify your own comments before posting them and contradicting somebody else.

Mayank.
0
 
CleanupPingCommented:
tttntt:
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
EXPERTS:
Post your closing recommendations!  No comment means you don't care.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Split points between mayankeagle and funnyveryfunny.
0
 
Mayank SAssociate Director - Product EngineeringCommented:
Ok with me.
0
 
funnyveryfunnyCommented:
Me too :-)
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Tackle projects and never again get stuck behind a technical roadblock.
Join Now