BinarySearch,Sort and Reverse Method of ArrayList in C# (Part – 40)

The ArrayList class provides a number of properties and methods that are used to work with an ArrayList. In this article, I’m going to describe three important methods of the ArrayList class, which are:

1.BinarySearch(): Performs a binary search on the ArrayList.
2.Sort(): Sorts the items in the ArrayList.
3.Reverse(): Reverses items in the ArrayList.

Namespace: System.Collections.Generic

Assembly: mscorlib (in mscorlib.dll)


The BinarySearch method of the ArrayList class implements the binary searching algorithm. This uses a “divide and conquer” approach to finding the correct element, and only works on a pre-sorted array. For this reason, never use BinarySearch if your ArrayList might not be sorted.

The BinarySearch method returns the 0-based index of the object if it’s found. If the object is not found in the list, BinarySearch returns –1.


Sorting an ArrayList is done in many programs that use ArrayList, as sorting provides a view of the data that is helpful for both users and computers. The Sort method in the base class libraries is a parameterless instance method on ArrayList.

The ArrayList.Sort() used Quick algorithm to sort the element of Arraylist class. The QuickStort algorithm is a comparison sort (also called an unstable sort), which means that a “less than or equal to” comparison operation determines which of two elements should occur first in the final sorted list. However, if two elements are equal, their original order might not be preserved. In contrast, a stable sort preserves the order of elements that are equal. To perform a stable sort, you must implement a custom IComparer interface to use with the other overloads of this method.

When we call Sort() on the ArrayList, the default implementation of IComparer is called which uses QuickSort. QuickSort calls the IComparable implementation of CompareTo() on each of your objects in the ArrayList.



The ArrayList.Reverse() method are used to reverse the order of element of the ArrayList class such that the element at ArrayList [i], where i is any index within the range, moves to ArrayList [j], where j equals index + index + count – i – 1. The Reverse method is Overloded. The simplest form of this method uses the following declaration:



© 2015, www.techkatak.com. All rights reserved.