Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create First_and_last_occurrence_in_array #413

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions First_and_last_occurrence_in_array
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
#include <iostream>
using namespace std;

int firstOcc(int arr[],int n,int key){
int s=0,e=n-1;
int mid = s + (e-s)/2;
int ans =-1;
while (s<=e){
if (arr[mid]==key){
ans = mid;
e=mid - 1;

}
else if (arr[mid]>key){
e=mid-1;

}
else {
s=mid+1;

}
mid = s + (e-s)/2;
}
return ans;


}
int lastOcc(int arr[],int n,int key){
int s=0,e=n-1;
int mid = s + (e-s)/2;
int ans =-1;
while (s<=e){
if (arr[mid]==key){
ans = mid;
s=mid + 1;

}
else if (arr[mid]>key){
e=mid-1;

}
else {
s=mid+1;

}
mid = s + (e-s)/2;
}
return ans;
}
int main(){
int arr[6]={1,2,2,3,3,4};
cout<<" First occurrence of 2 is: "<<firstOcc(arr,6,2)<<endl;
cout<<" Last occurrence of 2 is: "<<lastOcc(arr,6,2)<<endl;

return 0;
}