[英]I don't understand why my code for binary search displays a segmentation error
我已經測試了向量 a = {1,5,8,12,13} 和 x = 23 的代碼,它向我發送了一個分段錯誤,我不明白為什么:
#include <iostream>
#include <cassert>
#include <vector>
#include <cmath>
using std::vector;
int binary_search(const vector<int> &a, int x) {
int left = 0, right = (int)a.size();
if(left>right) return -1;
right = floor((double)(left + right)/2);
if(a[right] == x){
return right;
}
else if(a[right]>x){
vector<int> w(a.begin(), a.begin() + right);
return binary_search(w,x);
}
else{
vector<int> w(a.begin() + right, a.end());
return binary_search(w,x);
}
}
當程序創建的向量 w 的大小為 1 時,它應該進入無限循環,不是嗎?
我們可以有索引start
和end
,它們可以指向要進行二進制搜索的子數組,這樣我們就不必顯式創建子數組。
int binary_search(vector<int> &a, int start, int end, int x) {
if(start > end)
return -1;
int mid = floor((double)(start + end)/2);
if(a[mid] == x){
return mid;
}
else if(a[mid] > x){
return binary_search(a, 0, mid - 1, x);
}
else{
return binary_search(a, mid + 1, end, x);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.