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

0

 



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


public class indexOfLastOccur {
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};
System.out.println(indoflastocc(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 !