I’ve read about binary searches on Wikipedia for the first time today and just skimmed the surface a bit. It seems it’s used to find items in a collection quickly where memory is sparse.
In a .NET/C# context, would I ever need to use one? Do you ever use them while building production actual-real-world software?
I’m sorry if this questions comes off as inciting, but I’m asking a genuine question as a student!
List<T>has a BinarySearch method, as does Array. You would use them if you had a sorted list and needed to find an element. Because they return an index, you can do things you can’t with a straight dictionary like find the largest element less than a key.One place I’ve used a binary search in real-world software is for doing range searches. Shipping rates are given for weight range, so there might be one rate for 0-1 lb, one for 1-5 lb, and one for 5-10 lb. If I call
List<T>.BinarySearchand look for 4 lb, it will give me the first index higher than 4 lb, which I can use the find the 1-5 lb range. A dictionary would just tell me that 4 lb was not found.For general sorted data, you are often better off using SortedList or SortedDictionary.