题目描述
实现二分查找函数,函数接口如下。
#include "binSearch.h"
int binSearch(const int s[], const int size, const int target)
{
// 请将实现代码添加在这里
}
size为数组s的实际大小。
假定s非递减有序,如果s中存在值为target的元素,
则返回最后一次出现的位序号,否则返回-1表示不存在。
位序号从0开始计。
调用样例
int s[8] = {0,1,1,3,3,3,6,6};
cout << binSearch(s,8,3) << endl; //输出5
cout << binSearch(s,8,4) << endl; //输出-1
//"binSearch.h"
# ifndef BIN_SEARCH_H
# define BIN_SEARCH_H
int binSearch(const int s[], const int size, const int target);
# endif
zhc的answer:
//binSearch.cpp
int binSearch(const int s[], const int size, const int target)
{
int bottom = 0 ;
int top = size-1 ;
int index = -1 ;
while(bottom <= top ){
int mid = (bottom+top)/2 ;
if( s[mid] > target ) top = mid-1 ;
else{
bottom = mid+1 ;
if(s[mid] == target) index=mid ;
}
}
return index;
}
Yizuodi的答案
#include "binSearch.h"
int binSearch(const int s[], const int size, const int target)
{
int bottom = 0 ;
int top = size - 1 ;
int index = -1 ;//默认不存在
while( bottom <= top ){
int mid = (bottom+top)/2 ;
if( s[mid] > target )
{
top = mid - 1 ;
}
else
{
bottom = mid + 1 ;
if(s[mid] == target)
{
index = mid ;
}
}
}
return index;
}