#include <bits/stdc++.h>
using namespace std;
int FindFirstOccurrence(vector<int> arr, int data)
{
int l = 0, r = arr.size() - 1;
int index = -1;
while (l <= r)
{
int mid = l + (r - l) / 2;
// store mid as found index and
// continue search in the l
if (arr[mid] == data)
{
index = mid;
r = mid - 1;
}
else if (arr[mid] > data)
{
r = mid - 1;
}
else
{
l = mid + 1;
}
}
return index;
}
int main()
{
vector<int> arr{4, 5, 6, 6, 6, 7, 8};
int data = 6;
int index = FindFirstOccurrence(arr, data);
if (index != -1)
cout << "The first occurrence of data " << data << " is at: " << index << endl;
else
cout << "data not found\n";
return 0;
}
Output
The first occurrence of data 6 is at : 2
0 Comments