DEV Community

alokz diptim!
alokz diptim!

Posted on

Binary search using c#

alt text

I'll be breaking down the documentation if you need help.

    public static int BinarySearch(int arraySize, int targetNumber)
    {

        Random random = new Random();
        int[] figures = new int[arraySize];

        while (!figures.Contains(targetNumber))
        {
            for (int i = 0; i < figures.Length; i++)
            {
                figures[i] = random.Next(0, 15);
            }
        }

        //SORTING OUT THE ARRAY
        Array.Sort(figures);

        int minimum = 0;
        int maximum = figures.Length - 1;

        l1:

        int center = (maximum + minimum) / 2;

        if (figures[center] == targetNumber)
        {
            return center;
        }

        if (minimum > maximum)
        {
            Console.WriteLine("This kind of Array doesnt exist and this is false. Please add some element to the element. Thanks!");
        }

        if (figures[center] < targetNumber)
        {
            minimum = center + 1;
        }

        if (figures[center] > targetNumber)
        {
            maximum = center - 1;
        }

        if (figures[center] == targetNumber)
        {
            return center;
        }

        goto l1;

    }

    static void Main(string[] args)
    {
        Console.WriteLine(BinarySearch(10, 8));

        Console.WriteLine("The End");
        Console.Read();
    }
}

}

Top comments (0)