

import java.util.Arrays;
import java.util.Scanner;

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

    public static final Scanner KBD = Common.KBD;
    private static final int HOW_MANY = 40;
    private static final int MAX = 100;
    private static int traceLevel = 0;

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

        setTraceLevel();

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

        // sort it
        int value = Common.randomNumber(MAX / 10, MAX);
        System.out.println("Searching for " + value + ":");
        int posn = linearSortedSearch(numbers, value);

        // show result
        if (posn >= 0) {
            System.out.println(value + " found at " + posn + ":");
            Common.printArray(numbers, posn, posn + 1);
        } else {
            System.out.println(value + " not found");
        }
        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 - tracing\n\n"
                + "Trace level: ";

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

    /**
     * Search the given array.
     *
     * @param arr the array to search
     * @param value the value to search for
     */
    public static int linearSortedSearch(int[] arr, int value) {
        for (int i = 0; i < arr.length; ++i) {
            if (traceLevel > 0) {
                System.out.println("Searching for " + value + "...");
                Common.printArray(arr, i, i + 1);
                Common.pause();
            }
            if (arr[i] == value) {
                return i;
            } else if (arr[i] > value) {
                return -1;
            }
        }
        return -1;
    }
}
