[英]Segmentation fault (core dumped) not able to debug the code for binary search with duplicates problem?
the problem is to return the lowest index of the element on a sorted list with duplicates.问题是返回具有重复项的排序列表中元素的最低索引。 but my code is giving segmentation error.I am not able to identify the error in code.
但我的代码给出了分段错误。我无法识别代码中的错误。
int binary_search(const vector<int> &a, int left, int right, int x)
{
// write your code here
if (right - left == 0)
return right;
while (right >= left)
{
int mid = right - left / 2;
if (a[mid] == x)
return binary_search(a, left, mid, x);
else if (a[mid] > x)
right = mid - 1;
else
left = mid + 1;
}
return -1;
}
int main()
{
int n;
std::cin >> n;
vector<int> a(n);
for (size_t i = 0; i < a.size(); i++)
{
std::cin >> a[i];
}
int m;
std::cin >> m;
vector<int> b(m);
for (int i = 0; i < m; ++i)
{
std::cin >> b[i];
}
for (int i = 0; i < m; ++i)
{
// replace with the call to binary_search when implemented
std::cout << binary_search(a, 0, (int)a.size() - 1, b[i]) << ' ';
}
}
When you find the result a[mid] == x
, store it & keep searching to the left portion for the lowest index.当您找到结果
a[mid] == x
时,将其存储并继续在左侧搜索最低索引。
int binary_search(const vector<int> &a, int left, int right, int x)
{
// write your code here
if (right - left == 0)
return right;
int idx = -1;
while (right >= left)
{
int mid = right - left / 2;
// modified
if (a[mid] == x) {
idx = mid;
right = mid - 1;
}
else if (a[mid] > x)
right = mid - 1;
else
left = mid + 1;
}
return idx;
}
PS: You might want to check the way you're calculating mid
value, Usually, mid = (left + right) / 2
or mid = left + (right - left) / 2
to avoid overflow. PS:您可能需要检查计算
mid
值的方式,通常, mid = (left + right) / 2
或mid = left + (right - left) / 2
以避免溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.