不一样的二分查找-只比较一次的2分查找实现
程序员文章站
2024-01-09 21:59:16
...
int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while(low <= high) { mid = low + high; if (x < v[mid]) { high = mid - 1; } else if (x > v[mid]) { low = mid + 1; }else { return mid; } } return -1; }
int binsearch2(int x, int v[], int n) { int low, high, mid, cur; cur = -1; low = 0; high = n - 1; while (low <= high) { mid = (low + high) / 2; if (x < v[mid]) { high = mid -1; }else { cur = mid; low = mid + 1; } } return (cur != -1 && v[cur] == x)? cur : -1; }
第二种方式减少了循环内的比较次数,但是可能增加本身循环的次数(第一种方式,在mid=x时就可以退出循环了,但第二种的循环结束条件为low 〉high)但因为是o(logN)所以循环次数增加的不多,还没进行实际的性能测试,以后补上。