top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

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

+2 votes
772 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 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes
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 by Joy Dutta
Similar Questions
+4 votes

Write a program to make AVL tree buy arranging element in array ?

+4 votes

You have two arrays A1 and A2. Delete all element from A1 which are already in A2 and return new array.

+1 vote

Given 3 sorted array of size x, y, z. what is the minimum time taken to find the kth smallest element in the merged sorted array.

...