正确的二分查找算法时间:2022-12-27 19:14:46/** * binary search algorithm, correct and high performance; * this implementation will always return the first elment that equal to v; * and will avoid overflow when calc the middle; * and can reduce comparence count; * return -1 if not found; * pos if found */ int bin_search (int array[], int n, int v) { int left, right, middle; left = -1; right = n; while (left + 1 != right) { middle = left + (right - left) / 2; if (array[middle] < v) left = middle; else right = middle; } if (right >= n || array[right] != v) right = -1; return right; }