Q:

C# program to search an item in an array using binary search

belongs to collection: C# Basic Programs | array programs

0

C# program to search an item in an array using binary search

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

//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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | array programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
C# program to implement indexer for an integer arr... >>
<< C# program to produce a third array by appending t...