Binary Searching: Find last occurrence of element in array

Simple C program to find last occurrence index of an element in sorted array. For example if array is {34,45,45,45,56,57,57,68,78,78,78,78} then last occurrence of element 45 is at index 3 and last occurrence of element 78 is at index 11.

C Program:

#include<stdio.h>
int BSLOcurrence(int arr[],int size, int num)
{
	int low = 0, high = size-1;
	int mid;
	int last_oc = -1;
 
	while(low<=high)
	{
		mid = (low+high)/2;
 
		if(arr[mid]==num)
		{
			if(last_oc<mid)
			last_oc = mid;
			low = mid+1;
		}
		else
		if(arr[mid]<num)
		low = mid+1;
		else
		high = mid-1;
	}
 
	return last_oc;
}
 
int main()
{
	int arr[]={12,17,17,23,23,28,29,33,35};
 
	int size = sizeof(arr)/sizeof(arr[0]);
 
	int num;
	printf("Enter number: ");
	scanf("%d",&num);
 
	int index = BSLOcurrence(arr,size,num);
 
	if(index==-1)
	{
		printf("Number is not in array");
	}
	else
	{
		printf("Last occurrence index =  %d",index);
	}
 
	return 0;
}



Popular posts from this blog