BinarySearch method in ArrayList

In this article I will explain the BinarySearch method of arraylist.
  • 2232

Binarysearch(Object) method searches the entire sorted ArrayList for an element using the default comparer and returns the zero-based index of the element, that means it search in the sorted arraylist and give the index value at which the element is found.  

Example

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            ArrayList numbers = new ArrayList();

            numbers.Add(10);

            numbers.Add(22);

            numbers.Add(3);

            numbers.Add(5);

            numbers.Add(9);

            Console.WriteLine("The elements of the arraylist are:");

            foreach (int i in numbers)

            {

                Console.WriteLine(i);

            }

            numbers.Sort();

            Console.WriteLine("After sorting the elements of the arraylist are:");

            foreach (int i in numbers)

            {

                Console.WriteLine(i);

            }

            Console.WriteLine("The element 22 searched at:" + numbers.BinarySearch(22));

            Console.WriteLine("The element 10 searched at:" + numbers.BinarySearch(10)); 

        }

    }

}


Output

 

binaryserach.jpg 

 

Further Readings
 

Ask Your Question  

Got a programming related question? You may want to post your question here

 

Categories

More Articles

© 2019 DotNetHeaven. All rights reserved.