Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find modes of an array
#include <iostream>
#include <vector>
using namespace std;
void printArray(int *array, int size) {
for (int i = 0; i < size; i++)
{
printf("%d ", array[i]);
}
printf("\n");
}
void sortArray(int *array, int size){
for (int i = 0; i < size-1; i++)
{
int min = array[i];
int minLoc = i;
for (int j = i+1; j < size; j++)
{
if (array[j] < min)
{
minLoc = j;
min = array[j];
}
}
if (i != minLoc) {
int temp = array[i];
array[i] = array[minLoc];
array[minLoc] = temp;
}
}
}
void findModes(int *array, int size, vector<int> &modes){
sortArray(array, size);
vector<pair<int, int>> countInfo;
int count = 1;
for (int i = 1; i < size; i++)
{
if (array[i] == array[i - 1]) {
count++;
}
else
{
countInfo.push_back(pair<int,int>(array[i-1],count));
count = 1;
}
}
countInfo.push_back(pair<int, int>(array[size-1], count));
int max = 0;
for (int i = 0; i < countInfo.size(); i++) {
if (countInfo[i].second > max)
max = countInfo[i].second;
}
for (int i = 0; i < countInfo.size(); i++)
{
if (countInfo[i].second == max)
modes.push_back(countInfo[i].first);
}
}
int main() {
const int size = 10;
int array[size] = {5, 5, 1, 9, 9, 8, 8, 4, 6, 20};
vector<int> modes;
findModes(array, size, modes);
printf("Mode(s) of the array: ");
for (int i = 0; i < modes.size(); i++)
{
printf("%d ", modes[i]);
}
printf("\n");
printArray(array, size);
sortArray(array, size);
printArray(array, size);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment