BinarySearch(Object, IComparer) method in ArrayList

In this article I will discuss the BinarySearch(Object, IComparer) method of ArrayList.
  • 3259

Introduction

BinarySearch(Object, IComparer) method of ArrayList searches the entire sorted ArrayList for an element using the specified comparer and returns the zero-based index of the element.For example If we want to search any object from the arraylist then firstly the arraylist should be sorted then we perform searching.

Example

public class SimpleStringComparer : IComparer

{

    int IComparer.Compare(object x, object y)

    {

       int cmpstr = (int)x;

        return cmpstr.CompareTo((int)y);

    }

}

public class MyArrayList : ArrayList

{

    public static void Main()

    {

        // Creates a new ArrayList.

        MyArrayList numbers = new MyArrayList();

        numbers.Add(10);

        numbers.Add(21);

        numbers.Add(54);

        numbers.Add(3);

        numbers.Add(2);

        numbers.Add(10);

        numbers.Add(5);

        //display the array

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

        foreach (int i in numbers)

        {

            Console.WriteLine(i);

        }

        // BinarySearch requires a sorted ArrayList.so perform sorting in arraylist by using sort() method

        numbers.Sort();

        //display the sorted element

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

        foreach (int i in numbers)

        {

            Console.WriteLine(i);

        }  

        //perform searching

        int index = numbers.BinarySearch(10, new SimpleStringComparer());

        Console.WriteLine("Binary search, item found at index:{0}", index);

    }   

}


Output

 

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