posted 4 years ago
Hello,
Do you know it minimum and maximum?
Assume that the original array is a.
If not, find them with a single loop. Assume they are max and min.
Create a 1-d array (freq)with max-min+1 elements and initialize its elements to zeros.
Now take one element from the original array, a, and calculate k=element value - min. Increment freq[k] by one.
Like this freq array contains frequencies.
This is a linear order method.
#include<iostream>
using namespace std;
int frequency(int a[], int n, int x)
{
int count = 0;
for (int i=0; i < n; i++)
if (a[i] == x)
count++;
return count;
}
// Driver program
int main() {
int a[] = {0, 5, 5, 5, 4};
int x = 5;
int n = sizeof(a)/sizeof(a[0]);
cout << frequency(a, n, x);
return 0;
}
I hope this will help you