普通人的二分查找
int primary_binary_search(int* nums, int numsSize, int target) {
if (numsSize <= 0 || nums == NULL) {
return -1;
}
if (target < nums[0] || target > nums[numsSize - 1]) {
return -1;
}
if (target == nums[0]) {
return 0;
}
if (target == nums[numsSize - 1]) {
return numsSize - 1;
}
int head = 0;
int tail = numsSize - 1;
int mid = (head + tail) / 2;
while (mid != head) {
if (target == nums[mid]) {
return mid;
} else if (target > nums[mid]) {
head = mid;
} else {
tail = mid;
}
mid = (head + tail) / 2;
}
return -1;
}
高手写的二分查找
int binary_search(int *nums, int numsSize, int target) {
int head = 0;
int tail = numsSize - 1;
int mid;
while (head <= tail) {
mid = (head + tail) >> 1;
if (nums[mid] == target) return mid;
if (nums[mid] < target) {
head = mid + 1;
} else {
tail = mid -1;
}
}
return -1;
}
差别在哪里?
- 前一个程序冗长
if (target < nums[0] || target > nums[numsSize - 1]) {
return -1;
}
if (target == nums[0]) {
return 0;
}
if (target == nums[numsSize - 1]) {
return numsSize - 1;
}
上面的这种特殊情况判断真的需要吗?
真的不需要,原因:
1)More Code,More bug.
2) 二分查找的效率非常高,从一个32位的最大长度的数组中查找仅需要32次二分,没必要为了微不足道的效率,添加特殊处理。
3)特殊处理影响代码的美观与整洁。
- 效率
1)位运算效率更高。
mid = (head + tail) / 2;
替换为:
mid = (head + tail) >> 1;
2)不做任何的重复
head = mid;
提换为:
head = mid + 1;