Skip to content

Commit

Permalink
Merge pull request #432 from a-ayush19/master
Browse files Browse the repository at this point in the history
Most frequent element in an array
  • Loading branch information
fineanmol committed Oct 2, 2021
2 parents 36bee6b + 2c542b9 commit 103dfb4
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions Contributors.html
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@
<a class="box-item" href="https://github.com/yamini236"><span>Yamini Bansal</span></a>
<a class="box-item" href="https://github.com/whatiskeptiname"><span>Susan Ghimire</span></a>


<a class="box-item" href="https://github.com/NitulKalita"><span>Nitul</span></a>
<a class="box-item" href="https://github.com/jash-kothari"><span>Jash Kothari</span></a>
<a class="box-item" href="https://github.com/SimonUR"><span>Simon</span></a>
Expand All @@ -588,6 +589,7 @@
<a class="box-item" href="https://github.com/MFR414/"><span>M Firmansyah Rifai</span></a>
<a class="box-item" href="https://github.com/AdityaSawant21"><spann>Aditya Sawant</span></a>
<a class="box-item" href="https://github.com/kevadamar"><spann>Keva Damar Galih</span></a>
<a class="box-item" href="https://github.com/a-ayush19"><span>Ayush Awasthi</span></a>


<!-- Please maintain the alignment... -->
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#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;
}

// driver program
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;
}

0 comments on commit 103dfb4

Please sign in to comment.