Created
November 29, 2020 10:12
-
-
Save abhishek2x/7d3e2105215385d5eab6aa526aa14fa3 to your computer and use it in GitHub Desktop.
Finding First and Last Occurance an Element in a Sorted Array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Finding First and Last Occurance an Element in a Sorted Array | |
#include <bits/stdc++.h> | |
using namespace std; | |
#define ll long long int | |
int main(){ | |
ios :: sync_with_stdio(false); | |
cin.tie(0); | |
vector<int> v = {1, 3, 10, 10, 10, 12, 13}; | |
int l, r, mid, x=10; | |
l = 0; | |
r = v.size()-1; | |
int firstOccr, lastOccr; | |
while(l<=r){ | |
mid = (r+l)/2; | |
if(v[mid] == x){ | |
firstOccr = mid; | |
r = mid-1; | |
} else if(v[mid] > x){ | |
r = mid - 1; | |
} else { | |
l = mid + 1; | |
} | |
} | |
l = 0; | |
r = v.size()-1; | |
while(l<=r){ | |
mid = (r+l)/2; | |
if(v[mid] == x){ | |
lastOccr = mid; | |
l = mid+1; | |
} else if(v[mid] > x){ | |
r = mid - 1; | |
} else { | |
l = mid + 1; | |
} | |
} | |
cout << firstOccr << " " << lastOccr; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment