折半查找主要用于有序数组中查找某一特定元素。
c#实现/// <summary> /// 折半查询,适用于顺序字符中查找,比如:int[]{0,1,2,3,4,5,6,7,8,9}中查找8,或者英文字典中查找某个单词 /// </summary> public class BinarySearching { List<int> _list; int left, right, middle; public BinarySearching(List<int> list) { _list = list; left = 0; right = list.Count - 1; } public int Search(int t) { int rest = -1; if (_list == null) return rest; if (_list[0] == t) return _list[0]; if (_list[_list.Count - 1] == t) return _list[_list.Count - 1]; while (true) { middle = (left + right) / 2; if (left == right) { if (t == _list[right]) { rest = _list[right]; } break; } else if (t == _list[middle]) { rest = _list[middle]; break; } else if (t > _list[middle]) { left = middle + 1; } else if (t < _list[middle]) { right = middle - 1; } } return rest; } }