Binary Searching: Find first occurrence of element in sorted array
Binary searching is an algorithm to search an element in sorted array. Here is C program to find first occurrence of an element in array.
For example if array is {12,12,14,15,15,15,16,16,19,22} then first occurrence of element 12 is at index 0, first occurrence of element 15 is at index 3.
C Program:
For example if array is {12,12,14,15,15,15,16,16,19,22} then first occurrence of element 12 is at index 0, first occurrence of element 15 is at index 3.
C Program:
#include<stdio.h> int BSFOcurrence(int arr[],int size, int num) { int low=0, high=size-1, mid; /* Initialize a variable to find first occurrence to size of array. */ int first_oc = size; while(low<=high) { mid = (low+high)/2; if(arr[mid]==num) { if(mid<first_oc) first_oc = mid; high = mid-1; } else if(arr[mid]<num) low = mid+1; else high = mid-1; } return first_oc; } int main() { int arr[]={12,13,16,16,19,22,22,25,28}; int size = sizeof(arr)/sizeof(arr[0]); int num; printf("Enter number "); scanf("%d",&num); int index = BSFOcurrence(arr,size,num); if(index == size) { printf("Number is not in array\n"); } else { printf("First occurrence at index = %d",index); } return 0; }