Astrodevil / Programming-Basics

This Repository Contains source codes of various programming languages. Please Contribute to make this Useful.
https://astrodevil.github.io/Programming-Basics/
MIT License
72 stars 121 forks source link

Most frequent element in an array in C++ #256

Closed ayush-1909 closed 3 years ago

ayush-1909 commented 3 years ago

I wanna add most frequent element in an array in C++ in the DSA directory.

Kindly assign it to me.

you can have a look at the code.

include <bits/stdc++.h>

using namespace std;

int mostFreq(int arr[], int n) { // Sorting sort(arr, arr + n);

// using linear traversal
int max_count = 1, res = arr[0], curr_count = 1;
for (int i = 1; i < n; i++) {
    if (arr[i] == arr[i - 1])
        curr_count++;
    else {
        if (curr_count > max_count) {
            max_count = curr_count;
            res = arr[i - 1];
        }
        curr_count = 1;
    }
}

// if most freq = last element
if (curr_count > max_count)
{
    max_count = curr_count;
    res = arr[n - 1];
}

return res;

}

int main() { //array int arr[] = { 1, 7, 2, 3, 3, 2, 3 }; int n = sizeof(arr) / sizeof(arr[0]); cout << mostFreq(arr, n); return 0; }

snehadaripa commented 3 years ago

Please assign this issue to me, I'll fix it.