Binary Search Algorithm in C# (min, max, middle position)

class BinarySearch
    {

        public static int Find(List<int> list, int searched)
        {
            //First sort input
            BucketSort.Execute(list, ShellSort.Execute);

            //Find min position
            int min = 0;
            //Find max position
            int max = list.Count - 1;

            int loops = 0;

            do
            {
                //Find middle position
                int middle = (min + max) / 2;

                if (searched < list[middle])
                {
                    //Bring down max so we half the search span the next time.
                    max = middle - 1;
                }
                else if (searched > list[middle])
                {
                    //Bring up min so we can half the search span the next time.
                    min = middle + 1;
                }
                else
                {
                    Console.WriteLine($"Loop Counter: {loops}");

                    //This is the item
                    return middle;
                }

                loops++;
            }
            while (min <= max);

            Console.WriteLine($"Loop Counter: {loops}");
            return -1;
        }        
    }

Comments

Popular posts from this blog

Enable Visual Studio to use more than 2GB of memory

Firefox and Chrome dark mode

Dealing with the morons who built Dell 7710 and RAID