Try to solve binary search question using c++

Viewed 30

Question:

Given a sorted array having N elements, find the indices of the first and last occurrences of an element X in the given array.

Input : arr[] = {1, 3, 5, 5, 5, 5, 7, 123, 125 }, 
x = 7
Output : First Occurrence = 6

but they will give output what will I do wrong :

5

code:

#include<iostream>
using namespace std;
int main(){

    int arr[]={1, 3, 5, 5, 5, 5, 7, 123, 125};
    int start=0;
    int end=(sizeof(arr)/sizeof(arr[0]))-1;
    int x=7;
    int mid;
    int result;
    while(start<end){
        mid=(start+end)/2;
        if(arr[mid]<x){
            start=mid+1;
        }
        else if(arr[mid]==x){
            end=mid-1;
        }
    }
    cout<<"first occuerence"<<start;
}
0 Answers
Related