C++求众数
#include<iostream>
using namespace std;
const int N = 101;
int a[N];
int sum[N];
int position[N];
void quick_sort(int l, int r, int q[],int p[])
{
if (l >= r) return;
int i = l - 1, j = r + 1, x = q[(l + r) >> 1];
while (i < j)
{
do i++; while (q[i] < x);
do j--; while (q[j] > x);
if (i < j) {
swap(q[i], q[j]);
swap(p[i], p[j]);
}
}
quick_sort(l, j, q,p);
quick_sort(j + 1, r, q,p);
}
int main()
{
sum[0] = 1;
int n,flag=1;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a[i];
position[i] = i;
}
quick_sort(0, n - 1, a,position);
for (int i = 0; i < n; i++)
{
if (a[i + 1] == a[i]) sum[i + 1] = sum[i]+1;
else sum[i + 1] = 1;
position[i] = i;
}
quick_sort(0, n - 1, sum, position);
for (int i = n - 1; i > 0; i--)
{
if (sum[i] != sum[i - 1]) break;
flag++;
}
if (flag < n)
cout << "该数列的众数有" << flag << "个" << endl;
else {
cout << "该数列没有众数";
return 0;
}
for (int i =n-1;flag>0; i--,flag--)
{
cout << "众数为:" << a[position[i]]<<",";
cout << "其出现的次数为:" << sum[i]<<endl;
}
return 0;
}