

import java.util.Scanner;

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

    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"
                + "Selection 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
        selectionSort(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 selectionSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; ++i) {
            int p = i;
            for (int j = i + 1; j < arr.length; ++j) {
                if (traceLevel > 1) {
                    System.out.println("...looking for smaller than " + arr[p]
                            + "...");
                    Common.printTwoOf(arr, j, p);
                    Common.pause();
                }
                if (arr[j] < arr[p]) {
                    p = j;
//                    if (traceLevel > 1) {
//                        System.out.println("...found new smallest: " + arr[p] 
//                                + "...");
//                        Common.pause();
//                    }
                }
            }
            Common.swap(arr, i, p);
            if (traceLevel > 1) {
                System.out.println("...swapped smallest into position...");
                Common.printTwoOf(arr, i, p);
                Common.pause();
            }
            if (traceLevel > 0) {
                System.out.println("one more selected: ");
                Common.printArray(arr, 0, i + 1);
                Common.pause();
            }
        }
    }

}
