BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Algorithms and Data Structures
.NET 1.1+

Binary Search Algorithm

The binary search algorithm provides fast searching within sorted arrays or collections. This iterative approach to searching disregards approximately half of the values in the collection with each pass to give O(log n) scalability.

Testing the Method

To try out the search algorithm, add the following code to the Main method and step through the code in the debugger to see the results. You can see that half of the searches yield the index of the search item, whilst the other half return -1 because the item being searched for is not present.

int[] items = new int[]
    { 10, 15, 18, 25, 29, 31, 36, 41, 44, 48, 49, 50, 52, 54, 58, 61, 65, 70, 95, 99 };

int index;
index = BinarySearch(items, 36);            // 6
index = BinarySearch(items, 37);            // -1
index = BinarySearch(items, 1000);          // -1
index = BinarySearch(items, 10);            // 0
index = BinarySearch(items, 99);            // 19
index = BinarySearch(new int[] { }, 1000);  // -1
31 July 2013