﻿/*
 * Problem 4. Binary search
 * Write a program, that reads from the console an array of N integers and an integer K,
 * sorts the array and using the method Array.BinSearch() finds
 * the largest number in the array which is ≤ K.
 */

using System;

class P04_BinarySearch
{
    static Random randomNumber = new Random();

    static void GenerateRandomArray(int[] array)
    {
        for (int i = 0; i <= array.GetUpperBound(0); i++)
        {
            array[i] = randomNumber.Next(-9, 10);
        }            
    }

    static void PrintArray(int[] array)
    {
        Console.Write("{ ");
        Console.Write(string.Join(", ", array));
        Console.Write(" }");
        Console.WriteLine();
    }

    static void Main()
    {
        // input and variable initialization
        Console.Write("array size: ");
        int size = int.Parse(Console.ReadLine());
        int[] array = new int[size];

        ////for (int i = 0; i < size; i++)
        ////{
        ////    Console.Write("element @ pos.{0}: ", i);
        ////    array[i] = int.Parse(Console.ReadLine());
        ////}

        // random array generation for easier homework check
        GenerateRandomArray(array);
        Console.WriteLine("Unsorted: ");
        PrintArray(array);

        Console.Write("number K: ");
        int range = int.Parse(Console.ReadLine());

        Array.Sort(array);
        Console.WriteLine("Sorted: ");
        PrintArray(array);

        int result = int.MinValue;

        for (int i = 0; i <= array.GetUpperBound(0); i++)
        {
            if (array[i] <= range && array[i] >= result)
            {
                result = array[i];                                
            }
        }

        Console.WriteLine();
        Console.WriteLine("the biggest number <= K is {0}", result);
        Console.WriteLine();
    }
}