How to find the first occurrence of a number in sorted array in Java

0

 


In this tutorial we will learn about how to how to print first occurence of a number in a tutorial. We are given a sorted array and a number num, we have to find out the first occurence of num in the array.



class indexOfFirstOccur
{
public static int indoffirstocc(int arr[],int val)
{
int low=0,high=arr.length-1;
while(low<=high)
{
int mid=(low+high)/2;
if(arr[mid]==val && (arr[mid-1]!=val) || mid==0)
return mid;
else
{
if(val>arr[mid])
low=mid+1;
else{
if(val<arr[mid])
high=mid-1;
else{
high=mid-1;
}
}
}
}
return -1;
}
public static void main(String args[])
{
int arr[]={1,5,9,14,19,28,39,45,53,53,53,88};
System.out.println(indoffirstocc(arr,53));
}
}

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !