Sunday, 17 July 2016

Count Element Occurrence(Iterative)

/*  Count Element Occurrence */
/*
    Given a sorted array of integers, find the number of occurrences of a given target value.
    Your algorithm’s runtime complexity must be in the order of O(log n). If the target is not found in the array, return 0
    **Example : **
    Given [5, 7, 7, 8, 8, 10] and target value 8, return 2.
*/


 #include<iostream>  
 using namespace std;  
 int first(int *arr, int low, int high, int x){  
   int mid;  
   if(low > high){  
     return -1;  
   }  
   mid = low + (high - low) / 2;  
   if(arr[mid] == x && ((mid - 1) >= low && arr[mid - 1] < x)){  
     return mid;  
   } else if(arr[mid] > x){  
     return first(arr, 0, mid - 1, x);  
   }else{  
     return first(arr, mid + 1, high, x);  
   }  
 }  
 int last(int *arr, int low, int high, int x){  
   int mid;  
   if(low > high){  
     return -1;  
   }  
   mid = low + (high - low) / 2;  
   if(arr[mid] == x && ((mid + 1) <= high && arr[mid + 1] > x)){  
     return mid;  
   } else if(arr[mid] > x){  
     return first(arr, 0, mid - 1, x);  
   }else{  
     return first(arr, mid + 1, high, x);  
   }  
 }  
 int countOccurrences(int *arr, int n, int x){  
   int firstIndex = first(arr, 0, n - 1, x);  
   int lastIndex = last(arr, 0, n - 1, x);  
   cout << firstIndex << " " << lastIndex << endl;  
   //Element not found  
   if(firstIndex == -1){  
     return 0;  
   }  
   return lastIndex - firstIndex + 1;  
 }  
 int main(){  
   //int arr[] = {5, 7, 7, 7, 8, 8, 10};  
   int arr[] = {1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 10, 10, 10};  
   cout << countOccurrences(arr, sizeof(arr) / sizeof(arr[0]), 1);  
   return 0;  
 }  
Share:

0 comments:

Post a Comment

Contact Me

Name

Email *

Message *

Popular Posts

Blog Archive