First Occurrence of an element in the sorted array

 

First Occurrence of an element in the sorted array

As the given array is sorted so we can think of the implementation of binary search.


#include <iostream>

using namespace std;


int firstocc(vector<int>& nums, int target)

        {    int start = 0, end = nums.size()-1, ans=-1;

                while(start<=end)

                      {

                              int mid = end + (start-end)/2;

                        if(nums[mid]==target)

                        {

                                ans = mid;       // got the targeted element here

                                end = mid-1;    //checking for the first occurrence and it will be in left half 

                        }

                        else if(nums[mid]>target)

                                end = mid-1;

                        else 

                                start = mid+1;

                      }

                return ans;

        }


int main()

{

              vector <int> nums =  {1,2,6,6,6,6,8,10} ;

int target = 6;

              int ans =  firstocc( nums, target );

             cout<< "First occurrence of " << target << "is at index " << ans ;

             return 0;

}


output :

           First occurrence of  6 is  at index 2.

Post a Comment (0)
Previous Post Next Post