import java.util.*;
/** 
 * Bubble sort routine for arrays
 * @author Suzanne Balik, 6 Nov 2001
 * NOTE: This is a very simple, but not particularly 
 *       efficient sorting method
 * MODIFICATIONS: Stopped sort if a pass did not do any swaps
 *                Changed so that inner loop stopped 
 *                at the sorted end of the array each time.            
 *                SPB, 8 Nov 2001
 */
public class BubbleSort {

  public static void sort(int[] array) {
    
    boolean done = false;
    
    for (int i = 0; i < array.length - 1 && !done; i++) {
      
      done = true;
      
      for (int j = 0; j < array.length - 1 - i; j++) {
      
        if (array[j] > array[j + 1]) {
	  
	  done = false;
	  
	  int tmp = array[j];
	  
	  array[j] = array[j + 1];
	  
	  array[j + 1] = tmp;
	}
      }
    } 
  }
  
  public static String toString(int[] array) {
  
    String s = "[";
    for (int i = 0; i < array.length; i++)
      s += " " + array[i];
    s += " ]";
    return s;
  }
  
  public static void main(String[] args) {
  
    int[] array = {2, 8, 1, 3, 4, 5, 7, 6};
    
    System.out.println("Unsorted array: " + 
                        BubbleSort.toString(array));
    BubbleSort.sort(array);
    
    System.out.println("Sorted array:   " + 
                        BubbleSort.toString(array));
    if (args.length == 1) { 
      array = new int[Integer.parseInt(args[0])];
      Random generator = new Random();
      final int MAX = 200;
      for (int i = 0; i < array.length; i++)
        array[i] = generator.nextInt(MAX);
      //System.out.println("Unsorted array: " + 
                            BubbleSort.toString(array));
      long startTime = System.currentTimeMillis();
      BubbleSort.sort(array);
      long stopTime = System.currentTimeMillis();
      System.out.println("Time to sort " + args[0] + 
                         " random integers in range 1 - 200: " + 
			 (stopTime - startTime) + "ms");
      //System.out.println("Sorted array:   " + 
      BubbleSort.toString(array));
    }
  }
}