C# program to 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

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.


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);
            Console.WriteLine("Item does not found");

    public static void Main()
        int[] intArray = { 012,123, 345,456, 786};

        SearchItem(intArray, 786);


Item 786 found at index 4
Press any key to continue . . .


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 »


What's New (MCQs)

Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.