

import java.util.Scanner;

/**
 *
 * @author Mark Young (A00000000)
 */
public class InsertionSort {

    public static final Scanner KBD = Common.KBD;
    private static final int HOW_MANY = 10;
    private static final int MAX = 1000;
    private static int traceLevel = 0;

    public static void main(String[] args) {
        System.out.println("\n\n"
                + "Insertion Sort\n"
                + "==============\n");

        setTraceLevel();

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

        // sort it
        insertionSort(numbers);
        
        // show it sorted
        System.out.println("Array now sorted");
        Common.printArray(numbers);
        Common.pause();
    }

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

        System.out.print(traceMenu);
        traceLevel = KBD.nextInt();
        KBD.nextLine();
        while (traceLevel < 0 || 2 < traceLevel) {
            System.out.print(traceMenu);
            traceLevel = KBD.nextInt();
            KBD.nextLine();
        }
    }

    /**
     * Perform insertion sort on the given array.
     *
     * @param arr the array to sort
     */
    public static void insertionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; ++i) {
            int p = i + 1;
            int temp = arr[p];
            if (traceLevel > 1) {
                System.out.println("...inserting " + temp + "...");
                Common.printArray(arr, 0, i + 1);
                Common.pause();
            }
            while (p > 0 && arr[p - 1] > temp) {
                arr[p] = arr[p - 1];
                --p;
                if (traceLevel > 1) {
                    System.out.println("...inserting " + temp + "...");
                    System.out.println("...copy up " + arr[p] + "...");
                    Common.printArray(arr, 0, i + 2);
                    Common.pause();
                }
            }
            arr[p] = temp;
            if (traceLevel > 0) {
                System.out.println("one more inserted: ");
                Common.printArray(arr, 0, i + 2);
                Common.pause();
            }
        }
    }

}
