C# - Search an Item in an Array Using Binary Search

Here, we are going to learn how to search an item in an array using binary search in C#?
Submitted by Nidhi, on August 22, 2020 [Last updated : March 19, 2023]

Here we will search an item using binary search. The binary search is a searching technique used to search for items from a sorted array.

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

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.

C# Basic Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.