   # Write code to return the index of first occurrence of element of sorted array ??

178 views

1,1,2,2,2,6,6,6,7,7,7,7,7,7,7,8,8,9,9,9

Example:
Input = 1 Output=0 (First index of 1).
Input = 2 Output=2 (First index of 2).
Input = 6 Output= 5 (First index of 6).
Input = 7 Output= 8 (First index of 7).
Input = 8 Output=15 (First index of 8).
Input = 9 Output=17 (First index of 9). posted Jan 19, 2014

``````int FirstOccur(int Array[],int low,int high,int data)
{
int mid;

if(high>=low)
{
mid=(high+low)/2;//calculate the mid value

/*this condition says that when low index of the array becomes mid and data is less than mid-1,
then u can say mid is the first occurrence of that element as u r checking the first occurrence
of that element*/
if(mid==low&&Array[mid]==data||Array[mid]==data&&Array[mid-1]<data)
{
return mid;
}
else if(Array[mid]<=data)
{
return FirstOccur(Array,low,mid-1,data);
}
else
{
return FirstOccur(Array,mid+1,high,data);
}

}

return -1;
}
`````` answer Jun 30, 2014
Similar Questions