Find an element frequency in sorted array
Simple C program to calculate frequency of an element in sorted array. This program is based on divide and conquer method.
For example if array is {1,1,4,4,12,12,12,12,13,13,13,14}; then frequencies of elements are:
frequency of 1 is 2;
frequency of 4 is 2;
frequency of 12 is 4;
frequency of 13 is 3;
frequency of 14 is 1;
C Program:
For example if array is {1,1,4,4,12,12,12,12,13,13,13,14}; then frequencies of elements are:
frequency of 1 is 2;
frequency of 4 is 2;
frequency of 12 is 4;
frequency of 13 is 3;
frequency of 14 is 1;
C Program:
#include<stdio.h> int BSFreq(int arr[],int low,int high, int num) { if(high<low) return 0; int mid = (low+high)/2; /* If mid element is equal to target element then add one and break array in two part, one from index 0 to mid-1 and other from index mid+1 to high */ if(arr[mid]==num) return 1+BSFreq(arr,mid+1,high,num) +BSFreq(arr,low,mid-1,num); else if(arr[mid]<num) return BSFreq(arr,mid+1,high,num); else return BSFreq(arr,low,mid-1,num); } int main() { int arr[]={1,1,2,5,6,7,8,8,16,16,16,18}; int size = sizeof(arr)/sizeof(arr[0]); int num; printf("Enter a number: "); scanf("%d",&num); int freq = BSFreq(arr, 0,size-1, num); printf("Freq of %d is %d \n",num,freq); return 0; }