?
Solved

how to do a buble sort animation using java?

Posted on 2003-03-27
13
Medium Priority
?
352 Views
Last Modified: 2012-06-27
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
Comment
Question by:tttntt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
13 Comments
 
LVL 30

Expert Comment

by:Mayank S
ID: 8216685
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
 
LVL 4

Accepted Solution

by:
funnyveryfunny earned 152 total points
ID: 8217533
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
 
LVL 30

Assisted Solution

by:Mayank S
Mayank S earned 148 total points
ID: 8217738
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 4

Expert Comment

by:funnyveryfunny
ID: 8217956
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
 
LVL 101

Expert Comment

by:mlmcc
ID: 8218480
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
 
LVL 4

Expert Comment

by:funnyveryfunny
ID: 8220818
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 8222826
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
 

Expert Comment

by:CleanupPing
ID: 9474492
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
 
LVL 30

Expert Comment

by:Mayank S
ID: 9490473
Split points between mayankeagle and funnyveryfunny.
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 10789316
Ok with me.
0
 
LVL 4

Expert Comment

by:funnyveryfunny
ID: 10790607
Me too :-)
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
This article will show, step by step, how to integrate R code into a R Sweave document
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question