众数问题
2015-11-16 14:45
344 查看
#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; }
相关文章推荐
- 当前进程(Linux Devices Driver)
- raid 0,1,10,5特性
- forward内部跳转 和redirect重定向跳转的区别
- windows文件上传到linux系统的文件内容问题
- Spring学习笔记
- WdfRequestRetrieveOutputBuffer
- require.js 入门学习-备
- properties修改保留注解,重新加载properties到内存
- shell脚本sysbench-while语句和awk
- 实例代码详解jquery.slides.js
- HTML带有JS的加载
- 移动开发哪家强 ?ionic,react-native,native 三种开发方式对比!
- jquery可拖动表格调整列格子的宽度大小 本文章来源于 代潇瑞博客 原文地址:http://www.daixiaorui.com/read/98.html
- Windows 镂空图标,“百变硬汉”
- PowerDesigner 把Comment复制到name中和把name复制到Comment .
- 批量插入异常问题 There is no getter for property named ''
- linux centOS 安装mysql5.7.9
- Java基础编程之获取每一数位上的数
- 使用AIDL实现进程间的通信
- 关于git的常用的终端命令