How to Use Array.BinarySearch in C# - Simple Guide
Array.BinarySearch in C# to find the index of a value in a sorted array efficiently. It returns the index if found, or a negative number if not found. Make sure the array is sorted before using Array.BinarySearch for correct results.Syntax
The Array.BinarySearch method searches a sorted array for a specific value and returns its index if found.
Basic syntax:
int Array.BinarySearch(T[] array, T value)- Searches the entire sorted array.int Array.BinarySearch(T[] array, int index, int length, T value)- Searches a range within the array.
Parameters:
array: The sorted array to search.index: The starting index of the range to search.length: The number of elements in the range to search.value: The value to locate.
Returns the index of the value if found; otherwise, a negative number indicating the bitwise complement of the next larger element's index.
int Array.BinarySearch<T>(T[] array, T value); int Array.BinarySearch<T>(T[] array, int index, int length, T value);
Example
This example shows how to use Array.BinarySearch to find a number in a sorted integer array. It prints the index if found or a message if not found.
using System; class Program { static void Main() { int[] numbers = { 1, 3, 5, 7, 9, 11 }; int target = 7; int index = Array.BinarySearch(numbers, target); if (index >= 0) { Console.WriteLine($"Found {target} at index {index}."); } else { Console.WriteLine($"{target} not found in the array."); } } }
Common Pitfalls
1. Array must be sorted: Array.BinarySearch only works correctly if the array is sorted in ascending order. Searching an unsorted array can return incorrect results.
2. Negative return values: If the value is not found, the method returns a negative number. This number is the bitwise complement of the index where the value would be inserted to keep the array sorted.
3. Using the wrong range: When using the overload with index and length, ensure the range is valid and within array bounds.
using System; class Program { static void Main() { int[] unsorted = { 10, 2, 8, 4 }; int target = 4; // Wrong: searching unsorted array int wrongIndex = Array.BinarySearch(unsorted, target); Console.WriteLine($"Wrong search result: {wrongIndex}"); // Correct: sort first Array.Sort(unsorted); int correctIndex = Array.BinarySearch(unsorted, target); Console.WriteLine($"Correct search result: {correctIndex}"); } }
Quick Reference
Summary tips for using Array.BinarySearch:
- Always sort the array before searching.
- Check if the returned index is negative to know if the item was not found.
- Use the overload with
indexandlengthto search subranges. - Works with any array of types that implement
IComparable.