众数问题

来源:互联网 发布:linux svn回退版本号 编辑:程序博客网 时间:2024/06/05 17:58
#include "iostream"#include "algorithm"#include "fstream"using namespace std;//数组a[l,h]中,将小于a[l]的放其左,大于a[l]的放其右int partition(int y[], int l, int r){      int i = l, j = r+1;      int x = y[l];      while(true)    {           while(y[++i] < x);           while(y[--j] > x);           if(i>=j)              break;           swap(y[i], y[j]);      }      y[l] = y[j];      y[j] = x;      return j;  }//统计a[mid]出现的次数//minIndex记录a[mid]最左边下标,maxIndex记录a[mid]最右边下标int modeIndex(int a[], int &mid, int l, int h, int &minIndex, int &maxIndex){    int left = mid;    int right = mid;    while(a[--left] == a[mid] && left>=l);    while(a[++right] == a[mid] && right<=h);    left++;    right--;    minIndex = left;    maxIndex = right;    return maxIndex - minIndex + 1;}//number为a[l,h]的众数,count为重数void mode(int a[], int l, int h, int &number, int &count){    int index = partition(a, l, h); //众数下标    int minIndex, maxIndex;    int num = modeIndex(a, index, l, h, minIndex, maxIndex);  //统计a[index]出现的次数num    if(num > count)  //如果a[mid]出现次数比之前找到的众数出现次数多    {        number = a[index];  //更新众数        count = num;  //更新众数的个数    }    if(num < minIndex-l+1)  //如果a[index]左边的数大于num,向左递归        mode(a, l, minIndex-1, number, count);    if(num < h-maxIndex+1) //如果a[index]右边的数大于num,向右递归        mode(a, maxIndex+1, h, number, count);}int main(){    int n;    ifstream fin("number.txt");    fin >> n;    cout << "元素个数为:" << n << endl;    int *a = new int[n+1];    cout << "各元素为:\n";    for(int i=1; i<=n; i++)    {        fin >> a[i];        cout << a[i] << " ";    }    sort(a, a+n);    cout << endl;    int count = 0;    int number;    mode(a, 1, n, number, count);    cout << "众数为:" << number << endl;    cout << "重数为:" << count << endl;     fin.close();    return 0;} 

这里写图片描述

0 0