getting the mode in a sorted array

i'm stuck on how to get the mode of an array after sorting them out.

#include<iostream>
using namespace std;

int ascendingOrder();
int descendingOrder();
int mode();

int arr[5];

int main()
{
int num;

for(int x=0;x<5;x++)
{
cout<<"Enter no." <<x+1<< ": ";
cin>>arr[x];
}

cout<<"Elements after sorting out in ascending order."<<endl;
ascendingOrder();
cout<<"Elements after sorting out in descending order."<<endl;
descendingOrder();
mode();
}

int ascendingOrder()
{
for(int y=0;y<5;y++)
{
for(int z=0;z<5;z++)
{
if(arr[y]<arr[z])
{
int Num=arr[y];
arr[y]=arr[z];
arr[z]=Num;
}
}
}

for(int y=0;y<5;y++)
{
cout<<arr[y]<<endl;
}
}

int descendingOrder()
{
for(int y=0;y<5;y++)
{
for(int z=0;z<5;z++)
{
if(arr[z]<arr[y])
{
int Num=arr[z];
arr[z]=arr[y];
arr[y]=Num;
}
}
}

for(int z=0;z<5;z++)
{
cout<<arr[z]<<endl;
}
}

int mode()
{
int tempCount = 1 , mode = 1 , lastNumber = arr[0];

for( int index = 1; index < 5; ++index )
{
if( lastNumber == arr[index] )
++tempCount;
else
{
lastNumber = arr[index];
if( tempCount > mode ){
mode = tempCount;
cout<<arr[index];
tempCount = 0;
}
}
}
}
Please edit your post and use code tags - http://www.cplusplus.com/articles/jEywvCM9/
Your sorting functions don't return anything, they should be void.
You don't use int num; anywhere.

It looks like this code works:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int mode(int length, int arr[]) {
    int mode = arr[0], tempMode = arr[0], count = 1, tempCount = 1;
    for(int index = 1; index < length; ++index)
    {
        if (tempMode == arr[index])
            tempCount++;
        if (tempMode != arr[index] || index == length - 1) {
            if (tempCount > count) {
                mode = arr[index - 1];
		count = tempCount;
            }
            tempMode = arr[index];
            tempCount = 1;
        }
    }
    return mode;
}


https://goo.gl/bSWibn
Last edited on
Topic archived. No new replies allowed.