In this tutorial we will learn about how to how to print total occurences of a number in a tutorial. We are given a sorted array and a number num, we have to find out the total occurences of num in the array.
public class NumOfOccur {
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 int indoflastocc(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{
low=mid+1;
}
}
}
}
return -1;
}
public static void main(String args[])
{
int arr[]={1,5,9,14,19,28,39,45,53,53,53,88};
int num=indoflastocc(arr, 53)-indoffirstocc(arr, 53)+1;
System.out.println(num);
}
}