Source of BubbleSort.java



  3: import java.util.Scanner;

  5: /**
  6:  *
  7:  * @author Mark Young (A00000000)
  8:  */
  9: public class BubbleSort {

 11:     public static final Scanner KBD = Common.KBD;
 12:     private static final int HOW_MANY = 10;
 13:     private static final int MAX = 1000;
 14:     private static int traceLevel = 0;

 16:     public static void main(String[] args) {
 17:         System.out.println("\n\n"
 18:                 + "Bubble Sort\n"
 19:                 + "===========\n");

 21:         setTraceLevel();

 23:         // create an array of random integers
 24:         int[] numbers = Common.randomNumbers(HOW_MANY, MAX / 10, MAX);
 25:         Common.printArray(numbers);
 26:         Common.pause();

 28:         // sort it
 29:         bubbleSort(numbers);
 30:         
 31:         // show it sorted
 32:         System.out.println("Array now sorted");
 33:         Common.printArray(numbers);
 34:         Common.pause();
 35:     }

 37:     /**
 38:      * Prompt for and read a level of tracing to do.
 39:      */
 40:     public static void setTraceLevel() {
 41:         String traceMenu = "Enter a trace level: \n"
 42:                 + "  0 - no tracing\n"
 43:                 + "  1 - outer loop only\n"
 44:                 + "  2 - inner loop as well\n\n"
 45:                 + "Trace level: ";

 47:         System.out.print(traceMenu);
 48:         traceLevel = KBD.nextInt();
 49:         KBD.nextLine();
 50:         while (traceLevel < 0 || 2 < traceLevel) {
 51:             System.out.print(traceMenu);
 52:             traceLevel = KBD.nextInt();
 53:             KBD.nextLine();
 54:         }
 55:     }

 57:     /**
 58:      * Perform bubble sort on the given array.
 59:      *
 60:      * @param arr the array to sort
 61:      */
 62:     public static void bubbleSort(int[] arr) {
 63:         String msg;
 64:         for (int i = arr.length - 1; i > 0; --i) {
 65:             for (int j = 0; j < i; ++j) {
 66:                 if (traceLevel > 1) {
 67:                     Common.printArray(arr, j, j + 2);
 68:                 }
 69:                 if (arr[j] > arr[j + 1]) {
 70:                     msg = "swap";
 71:                     Common.swap(arr, j, j + 1);
 72:                 } else {
 73:                     msg = "ok";
 74:                 }
 75:                 if (traceLevel > 1) {
 76:                     System.out.println("...." + msg + "....");
 77:                     Common.pause();
 78:                 }
 79:             }
 80:             if (traceLevel > 0) {
 81:                 System.out.println("One more bubbled up");
 82:                 Common.printArray(arr, i, arr.length);
 83:                 Common.pause();
 84:             }
 85:         }
 86:     }

 88: }