算法思路:
1,设置整形数组A中元素,获得元素个数N
2,sort(A)
3,初始化查询起始指针,first->A,last->NULL,查询值find_value <- *first
4,do
5, last <- upper_bound(first,A+nSize,find_value)
6, 根据first,last查询起始指针显示查询元素及出现频度
7, first <- last
8, if first != A+nSize then find_value<- *first
9,while first != A+nSize
示例代码:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1,3,2,3,4,3,6,3};
int nSize = sizeof(A) / sizeof(int);
sort(A,A+nSize);
int *first = A;
int *last = NULL;
int find_value = A[0];
do
{
last = upper_bound(first,A+nSize,find_value);
cout << "find_value = " << find_value << "\t频度:" << (float)(last-first)/nSize << endl;
first = last;
if(first != A+nSize)
find_value = *first;
}while(first != A+nSize);
return 0;
}
方法2,先用sort排序,再用unique_copy去掉重复值,之后再利用count计数:
但是效率要低一些,因为利用了unique_copy函数获得了待查询的元素集合。其次利用了count计数。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1,3,2,3,4,3,6,3};
int nSize = sizeof(A) / sizeof(int);
sort(A,A+nSize);
vector<int> tmp;
unique_copy(A,A+nSize,back_inserter(tmp));
for(int i = 0 ;i < tmp.size();i ++)
{
int n = count(A,A+nSize,tmp[i]);
cout << "find_value = " << tmp[i] << "\t频度:" << (float)n/nSize << endl;
}
return 0;
}
下面再看一个和频度有关的例子:
在一个整数序列A[1..n],中,A中a出现次数大于50%,那么称a为多数元素:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
int A[] = {1,3,2,3,4,3,6,3};
int nSize = sizeof(A) / sizeof(int);
nth_element(A,A+nSize/2,A+nSize);
int find_value = *(A+nSize/2);
int nCount = count(A,A+nSize,find_value);
float ratio = (float)nCount / nSize;
if(ratio > 0.50f)
{
cout << "多数元素是:" << find_value << "\t频度:" << ratio << endl;
}
else
cout << "没有多数元素" << endl;
return 0;
}
该程序的算法思想是:如果多数元素频度大于50%,那么第n/2大或第n/2小元素可能就是多数元素,用nth_element函数就可以了,不必全排序