C++ 程序:使用修改的二分搜索查找给定数字的第一次出现
大家好!
在本教程中,我们将学习如何用 C++ 编程语言在排序数组中找到给定数字的第一次出现。
要详细了解二分搜索的概念,我们将推荐您访问二分搜索算法,我们已经在这里详细解释了这些概念。
为了更好地理解,请参考下面给出的注释良好的 C++ 代码。
代号:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
//Program to return the first occurance of b in the vector a
int first(int a[], int l, int h, int b)
{
int res = -1;
while (l <= h)
{
int m = (l + h) / 2;
if (a[m] == b)
{
res = m;
h = m - 1;
}
else if (a[m] > b)
{
h = m - 1;
}
else
{
l = m + 1;
}
}
return res;
}
int main()
{
cout << "\n\nWelcome to Studytonight :-)\n\n\n";
cout << " ===== Program to find the first occurance of a given number using Modified Binary Search ===== \n\n";
int i, n;
int a[] = {2, 3, 3, 4, 4, 4, 4, 4, 5};
n = sizeof(a) / sizeof(a[0]);
cout << "\n\nThe elements of the input sorted array are :\n\n";
for (i = 0; i < n; i++)
{
cout << a[i] << " ";
}
int k = 4; //the element to find the first occurance index of
//Calling first method to return the index of the first occurance of element k
int f = first(a, 0, n - 1, k);
cout << "\n\nThe index of the first occurance of " << k << " is: " << f;
cout << "\n\n\n";
return 0;
}
输出:
我们希望这篇文章能帮助你更好地理解二分搜索算法的概念,并使用它来找到给定数字的第一次出现及其在 CPP 中的实现。如有任何疑问,请随时通过下面的评论区联系我们。
继续学习: