由买买提看人间百态

boards

本页内容为未名空间相应帖子的节选和存档,一周内的贴子最多显示50字,超过一周显示500字 访问原贴
JobHunting版 - A Simple Question on Binary Search
相关主题
binary search什么时候用l问个变相的binary search的问题
求教一个onsite面试题目G questions
请问如何binary search出数组中的重复元素请问一下最大增长子序列的O(nLogk)算法
请问一道面试题如何回答这题:how to explain binary search tree to a 5 year old child
问一个关于binary search的问题Amazon Interview: algorithm for 2*LOG(N) up bound for search
听说binary search程序非常难写对,是吗?一个Amazon的面经
求个查找turn point的binary search codebinary search in rotated sorted array有重复时怎么办?
请教一个binary search tree和heap的问题。Google电面题
相关话题的讨论汇总
话题: arr话题: int话题: occurrence话题: binary话题: question
进入JobHunting版参与讨论
1 (共1页)
b*****n
发帖数: 143
1
"Programming Pearls" has a binary search program that searches the first
occurrence of a certain value. I think it is a little confusing so I wrote
it in another way:
/* Function that returns the first occurrence of x.
* arr is input sorted array, arr_size is the number of elements in arr,
* x is the value that we are looking for.
* Returns index of the element, or -1 if element is not found. */
int first_occurrence(int* arr, int arr_size, int x)
{
int l = 0;
int u = arr_size - 1;
while (l + 1 < u) {
int m = l + (u - l) / 2;
if (arr[m] < x)
l = m + 1; // line 8: both "l = m" and "l = m + 1" will work here?
else
u = m;
}
if (arr[l] == x)
return l;

if (arr[u] == x)
return u;
return -1;
}
My question is on line 8 (see the comments on that line). I tested a few
cases and it seems that both "l = m" or "l = m + 1" will work. Can anybody
confirm that? Thanks.
r*******n
发帖数: 3020
2
I think it's right.
loop invariant: x[l]<=t<=x[u] and x[l] is left most one.
at end of loop, u = l+1, and you check x[l] and x[u].
I can't find anything you miss.

first
wrote
arr,

【在 b*****n 的大作中提到】
: "Programming Pearls" has a binary search program that searches the first
: occurrence of a certain value. I think it is a little confusing so I wrote
: it in another way:
: /* Function that returns the first occurrence of x.
: * arr is input sorted array, arr_size is the number of elements in arr,
: * x is the value that we are looking for.
: * Returns index of the element, or -1 if element is not found. */
: int first_occurrence(int* arr, int arr_size, int x)
: {
: int l = 0;

b*****n
发帖数: 143
3
Thanks. Your confirmation makes me feel better.
1 (共1页)
进入JobHunting版参与讨论
相关主题
Google电面题问一个关于binary search的问题
问一道题听说binary search程序非常难写对,是吗?
square root的算法求个查找turn point的binary search code
代码写全对不容易请教一个binary search tree和heap的问题。
binary search什么时候用l问个变相的binary search的问题
求教一个onsite面试题目G questions
请问如何binary search出数组中的重复元素请问一下最大增长子序列的O(nLogk)算法
请问一道面试题如何回答这题:how to explain binary search tree to a 5 year old child
相关话题的讨论汇总
话题: arr话题: int话题: occurrence话题: binary话题: question