Bubble Sort – algorithm and example

Posted: October 10, 2011 in Java
The algorithm is 
for i = 1:n,
   for j = n:i+1, 
        if a[j] < a[j-1], 
            swap a[j,j-1]
      
Sample Program

public class BubbleSort {

 int array[] = {3, 5, 4, 2, 1 };
 int i, j, t = 0;

 for (i = 0; i < n; i++) {
            
       for (j = 1; j < (n - i); j++) {
            if (a[j - 1] > a[j]) {
              t = a[j - 1];
              a[j - 1] = a[j];
              a[j] = t;
            }
       }
      // printing each sort iteration result
      for (int x = 0; x < a.length; x++) {
                System.out.print(a[x] + "  ");
            }
            System.out.println();
        }


Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s