Source of InsertionSort.java



  3: import java.util.Scanner;

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

 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:                 + "Insertion 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:         insertionSort(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 insertion sort on the given array.
 59:      *
 60:      * @param arr the array to sort
 61:      */
 62:     public static void insertionSort(int[] arr) {
 63:         for (int i = 0; i < arr.length - 1; ++i) {
 64:             int p = i + 1;
 65:             int temp = arr[p];
 66:             if (traceLevel > 1) {
 67:                 System.out.println("...inserting " + temp + "...");
 68:                 Common.printArray(arr, 0, i + 1);
 69:                 Common.pause();
 70:             }
 71:             while (p > 0 && arr[p - 1] > temp) {
 72:                 arr[p] = arr[p - 1];
 73:                 --p;
 74:                 if (traceLevel > 1) {
 75:                     System.out.println("...inserting " + temp + "...");
 76:                     System.out.println("...copy up " + arr[p] + "...");
 77:                     Common.printArray(arr, 0, i + 2);
 78:                     Common.pause();
 79:                 }
 80:             }
 81:             arr[p] = temp;
 82:             if (traceLevel > 0) {
 83:                 System.out.println("one more inserted: ");
 84:                 Common.printArray(arr, 0, i + 2);
 85:                 Common.pause();
 86:             }
 87:         }
 88:     }

 90: }