Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Lower bound gives the address of first x exist in array or if doesn't exist
- then address of next element just greater than x.if next greater element element
- is not present in array,then address just after the array.
- Upper bound gives the address of just greater element than x.if not present in array,
- just next element after the end of array.
- */
- class Solution{
- public:
- /* if x is present in arr[] then returns the count
- of occurrences of x, otherwise returns 0. */
- int count(int arr[], int n, int x) {
- int *low = lower_bound(arr, arr+n, x);
- // If element is not present, return 0
- if (low == (arr + n) || *low != x)
- return 0;
- /* Else get the index of last occurrence of x.
- Note that we are only looking in the
- subarray after first occurrence */
- int *high = upper_bound(low, arr+n, x);
- return high - low;
- }
- };
- /*
- //Manual code of upper bound and lower bound of array
- int lower_bound(int arr[], int N, int X){
- int mid;
- // Initialise starting index and
- // ending index
- int low = 0;
- int high = N;
- // Till low is less than high
- while (low < high) {
- mid = low + (high - low) / 2;
- // If X is less than or equal
- // to arr[mid], then find in
- // left subarray
- if (X <= arr[mid]) {
- high = mid;
- }
- // If X is greater arr[mid]
- // then find in right subarray
- else {
- low = mid + 1;
- }
- }
- // if X is greater than arr[n-1]
- if(low < N && arr[low] < X) {
- low++;
- }
- // Return the lower_bound index
- return low;
- }
- // Function to implement upper_bound
- int upper_bound(int arr[], int N, int X)
- {
- int mid;
- // Initialise starting index and
- // ending index
- int low = 0;
- int high = N;
- // Till low is less than high
- while (low < high) {
- // Find the middle index
- mid = low + (high - low) / 2;
- // If X is greater than or equal
- // to arr[mid] then find
- // in right subarray
- if (X >= arr[mid]) {
- low = mid + 1;
- }
- // If X is less than arr[mid]
- // then find in left subarray
- else {
- high = mid;
- }
- }
- // if X is greater than arr[n-1]
- if(low < N && arr[low] <= X) {
- low++;
- }
- // Return the upper_bound index
- return low;
- }
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement