Below is s basic binary search implementation for a given sorted array. Binary Search is much more efficient than linear search, due to halfing the range for look ups. Native C# binary search has a cool feature that if the element is not found in the sorted array or list, it returns the inverted location in the data structure, which indicates the location that the item would be in that location, if the item would exists in the data structure, which turns very useful sometimes. Binary search is very adaptive and there are variations of binary search, such as you can start from the beginning if you dont know the range of the data structure. If the array or list is not sorted, then sorting it and doing binary search is waste, cause you can easily find the element in linear time by iterating through it.
public static int BinarySearch(IListlist, int item) { int index = (int)Math.Floor((double) (list.Count/2)); int startIndex = 0; int endIndex = list.Count - 1; while(true) { if(list[index] == item) { return index; } if(index - startIndex < 1 || endIndex-index <- 1) { return 0; } if(list[index] < item ) { // look right startIndex = index; index = (int) Math.Floor((double)(endIndex + index)/2); continue; } if(list[index] > item) { // look left endIndex = index; index = (int) Math.Floor((double) (index - startIndex)/2); continue; } } }
