forked from TheAlgorithms/C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path704.c
33 lines (31 loc) · 713 Bytes
/
704.c
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
int search(int *nums, int numsSize, int target)
{
int low = 0, high = numsSize - 1;
while (low <= high)
{
int mid = low + (high - low) / 2;
if (target > nums[mid])
{
low = mid + 1;
}
else if (target < nums[mid])
{
high = mid - 1;
}
else
{
return mid;
}
}
return -1;
}
/* Another solution: Using bsearch() */
int cmpint(const void *a, const void *b) { return *(int *)a - *(int *)b; }
int search(int *nums, int numsSize, int target)
{
int *ret = bsearch(&target, nums, numsSize, sizeof(int), cmpint);
if (ret)
return (ret - nums);
else
return -1;
}