-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_search.c
More file actions
43 lines (33 loc) · 847 Bytes
/
binary_search.c
File metadata and controls
43 lines (33 loc) · 847 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
* 常见题目:给定一个已排序数组,判断一个数是否在该数组中
* 如果在,返回改数在数组中的下标,否则返回-1
* 采用二分法查找
*/
#include <stdio.h>
#include <stdlib.h>
int binary_search(int *in, int size, int target)
{
int left, right, mid;
int i;
left = 0;
right = size - 1;
while(left <= right) {
mid = (right + left) >> 1;
printf("left %d, mid %d, right %d\n", left, mid, right);
if (in[mid] > target)
right = mid - 1;
else if (in[mid] < target)
left = mid + 1;
else
return mid;
}
return -1;
}
int main()
{
int in[] = {1, 4, 6, 9, 10, 11, 16, 44, 56, 66, 88};
int result;
result = binary_search(in, 11, 19);
printf("result %d\n", result);
return 0L;
}