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

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

Enable Visual Studio to use more than 2GB of memory