给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
#include<stdio.h>
int search(int *nums, int numsSize, int target)
{
int s = 0;
int e = numsSize -1;
int median;
while(s != e)
{
median = (e - s)/2 + s;
if(target > nums[median])
{
s = median + 1;
}
else if(target < nums[median])
{
e = median;
}
else
{
return median;
}
printf("mid = %d\n", median);
}
if(target == nums[s])
{
return s;
}
return -1;
}
int main()
{
int nums[6] = {-1, 3, 7, 11, 15, 33};
int result = search(nums, 6, -1);
printf("%d\n", result);
}