C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Here: Three values are looked up. The locations of "peach", "banana", and "apple" are looked up in the List.
Important: The List is in alphabetical order. BinarySearch won't work if your List or array is not already sorted.
And: It doesn't matter if you use numeric, alphanumeric, or ASCII sorting—BinarySearch will work with any of these.
C# program that uses BinarySearch
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<string> l = new List<string>();
l.Add("acorn"); // 0
l.Add("apple"); // 1
l.Add("banana"); // 2
l.Add("cantaloupe"); // 3
l.Add("lettuce"); // 4
l.Add("onion"); // 5
l.Add("peach"); // 6
l.Add("pepper"); // 7
l.Add("squash"); // 8
l.Add("tangerine"); // 9
// This returns the index of "peach".
int i = l.BinarySearch("peach");
Console.WriteLine(i);
// This returns the index of "banana".
i = l.BinarySearch("banana");
Console.WriteLine(i);
// This returns the index of "apple".
i = l.BinarySearch("apple");
Console.WriteLine(i);
}
}
Output
6
2
1
Info: Wikipedia states that binary search "makes progressively better guesses, and closes in on the location of the sought value."
Binary search algorithm: WikipediaNote: Microsoft states that the BinarySearch method on List, which we will use, "returns the zero-based index of the element" we request.
List.BinarySearch Method: Microsoft DocsInfo: As the number of elements grows, BinarySearch is faster than a linear search.
And: With huge collections, with millions of elements, the cost of building up a Dictionary could eclipse the time saved on lookup.
Dictionary