Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to use binary search to find a user defined number in an already sorted array. I have the binary search algorithm already but I do not know how to take the user input and search for it.

What I have tried:

Binary Search:
C#
static void BinarySearch(int[] arr, int key)
        {
            int minNum = 0;
            int maxNum = arr.Length - 1;

            while (minNum <= maxNum)
            {
                int mid = (minNum + maxNum) / 2;
                if (key == arr[mid])
                {
                    Console.WriteLine(++mid);
                }
                else if (key < arr[mid])
                {
                    minNum = mid - 1;
                }
                else
                {
                    maxNum = mid + 1;
                }
            }
            Console.WriteLine("None");
        }

Space I've tried to call it:
C#
Program p = new Program();
string userInput3;
Console.WriteLine("\nWhich number do you wish to search for in the array?");
userInput3 = Console.ReadLine();
int Int1 = Convert.ToInt32(userInput3);
int Int2 = int.Parse(userInput3);
p.BinarySearch(arr, userInput3);
Posted
Updated 11-Mar-20 11:39am
v2
Comments
gggustafson 11-Mar-20 23:41pm    
Why not use Array.BinarySearch?

1 solution

You have to parse user input to get a proper integer; and pass this integer to the function instead of array length:
C#
Console.WriteLine("\nWhich number do you wish to search for in the array?");
int key;
while (!int.TryParse(Console.ReadLine(), out key)) { }
BinarySearch(arr, key);
Here we keep trying to parse until it succeeds.
 
Share this answer
 
Comments
[no name] 11-Mar-20 17:51pm    
Thank you for the reply, I do also have one other question, how would I print whether the user input in actually in the array or not because my code doesn't seem to do that and I don't exactly know why? Thank you again.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900