The source code to search an item in an array using binary search in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
//Program to search an item in an array
//using binary search in C#.
using System;
class Demo
{
public static void SearchItem(int []array, int item)
{
int itemAtIndex = Array.BinarySearch(array, 0, array.Length, item);
if (itemAtIndex >= 0)
{
Console.WriteLine("Item "+item+" found at index "+itemAtIndex);
}
else
{
Console.WriteLine("Item does not found");
}
}
public static void Main()
{
int[] intArray = { 012,123, 345,456, 786};
SearchItem(intArray, 786);
}
}
Output:
Item 786 found at index 4
Press any key to continue . . .
Explanation:
In the above program, we created a class Demo that contains two static methods SearchItem() and Main(). The SerachItem() method is used to search an item from a sorted array using BinarySearch() method. The BinarySearch() method returns the index if the item is found in a specified array otherwise it returns a negative value.
In the Main() method, we created an integer array intArray and then we search item 786 in the array then it will be found at index 4 using BinaraySearch() method.
Program:
The source code to search an item in an array using binary search in C# is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
Output:
Explanation:
In the above program, we created a class Demo that contains two static methods SearchItem() and Main(). The SerachItem() method is used to search an item from a sorted array using BinarySearch() method. The BinarySearch() method returns the index if the item is found in a specified array otherwise it returns a negative value.
In the Main() method, we created an integer array intArray and then we search item 786 in the array then it will be found at index 4 using BinaraySearch() method.