package main
import (
"errors"
"fmt"
)
// 二分查找,必须是有序的切片,
// 每次取中间元素 跟 目标对比
func binarySearch(veclass="superseo">c []int, target int, left int, right int) (int, error) {
fmt.Printf("left = %d,right =%d\n", left, right)
if vec[right] < target {
return 0, errors.New("slice don't find target")
}
// 取中间元素
//index := left + (right-left)/2
index := left + (right-left)>>1
if vec[index] == target {
return index, nil
} else if vec[index] > target {
return binarySearch(vec, target, left, index-1)
} else {
return binarySearch(vec, target, index+1, right)
}
}
func main() {
vec := []int{2, 31, 42, 78, 102, 197, 1388, 9123}
num := 9123
index, err := binarySearch(vec, num, 0, len(vec)-1)
if err != nil {
fmt.Println(err)
}
fmt.Printf(" get index = %d\n ", index)
}
输出
C++版本get index = 7
#include
#include
#include
#include
#include
using namespace std;
class solution
{
public:
static int getPostIndex(vector &vec, int target)
{
if (vec.size() <= target)
{
return -1;
}
for (int left = 0, right = vec.size() - 1; left <= right;)
{
int min = ((right - left) >> 1) + left;
//cout << " min =" << min << endl;
if (target == vec[min])
{
return min;
}
else if (target < vec[min])
{
right = min - 1;
}
else
{
left = min + 1;
}
}
return -1;
}
};
int main()
{
//test();
int arr[1000000] = {};
int len = 1000000;
for (int i = 0; i < len; i++)
{
arr[i] = i + 2;
}
vector vec(arr, arr + len );
int target = 8888;
int ret = solution::getPostIndex(vec, target);
cout << "ret = " << ret << endl;
return 0;
}
输出
ret = 8886
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)