Binary search in C#

Viewed 304

I'm trying to make a binary search for a random array which has 10 numbers. When I run my code, and the number I input is a number within the random array, instead of just outputting "Found it" once, it will continuously output "Found it" until I close the program, but I can't understand what I've done to make it keep outputting "Found it".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Binary_Search
{
    class Program
    {
        static void Main(string[] args)
        {
            int n = 10; //10 values in array
            Random r = new Random();

            int b; //value to search
            int i; //loop control value

            int[] a = new int[n + 1];

            a[0] = 0; //starts at 0

            for (i = 1; i <= n; i++) // set the array up
                a[i] = a[i - 1] + r.Next(1, 10); // + random numbers from 1 to 10

            for (i = 1; i <= n; i++) 
                Console.WriteLine(" a[" + i + "] + " + a[i] + ": "); // outputs the numbers for each value of array

            Console.WriteLine();
            Console.ReadLine();

            Console.WriteLine("What number are you looking for?");

            b = int.Parse(Console.ReadLine()); // enter value that you want to find

            i = 1;

            Console.ReadLine();

            int min = 1;
            int max = n - 1;

            do
            {
                int mid = (min + max) / 2;

                if (a[mid] == b)
                {
                    Console.WriteLine("Found it");
                }
                else if (a[mid] > b)
                    max = mid;
                else if (a[mid] < b)
                    min = mid;
            } while (min <= max);

            Console.ReadLine();
        }
    }
}
2 Answers

You need to break/stop the loop once you've found it.

if (a[mid] == b)
{
    Console.WriteLine("Found it");
    break; // add this
}

The "Found it" message keeps getting printed because of your do-while condition. You get into an infinite loop because after several iterations, min equals to max. Set the condition to while (min < max); instead of while (min <= max); and have the if condition after the loop.

This should do the trick:

do
{
     int mid = (min + max) / 2;
     if (a[mid] > b)
         max = mid;
     else if (a[mid] < b)
         min = mid;
} while (min < max);

if (a[mid] == b)
{
     Console.WriteLine("Found it");
}
Related