#include <iostream>
using namespace std;
int firstOcc(int arr[], int n, int key) {
int start = 0;
int end = n-1;
int ans = -1;
int mid = start + (end-start)/2;
while (start <= end) {
if (arr[mid] == key) {
ans = mid;
end = mid - 1;
}
else if (arr[mid] < key) {
start = mid + 1;
}
else {
end = mid - 1;
}
mid = start + (end-start)/2;
}
return ans;
}
int lastOcc(int arr[], int n, int key) {
int start = 0;
int end = n-1;
int ans = -1;
int mid = start + (end-start)/2;
while (start <= end) {
if (arr[mid] == key) {
ans = mid;
start = mid + 1;
}
else if (arr[mid] < key) {
start = mid + 1;
}
else {
end = mid - 1;
}
mid = start + (end-start)/2;
}
return ans;
}
int main() {
int array[6] = {1,2,2,2,2,3};
int first = firstOcc(array,6,2);
cout << "first occurance of 2 is at index " << first << endl;
int last = lastOcc(array,6,2);
cout << "last occurance of 2 is at index " << last << endl;
return 0;
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter