(算法设计技巧与分析)Majority

来源:互联网 发布:淘宝卖家恶意不发货 编辑:程序博客网 时间:2024/06/04 06:33

#include<iostream>using namespace std;int Condidate(int a[],int n,int j);int main(){int count=0;int a[12]={1,1,1,1,1,1,2,2,2,2,2,2};int c=Condidate(a,12,0);for(int i=0;i<12;i++)if(a[i]==c)count++;if(count>11/2)cout<<"The majority in the array is "<<c<<endl;else cout<<"no majority!";return 0;}int Condidate(int a[],int n,int j){int x=a[j];int count=1;while(j<n&&count>0)if(a[++j]==x)count++;else count--;if(j==n)return x;else return Condidate(a,n,j+1);}


0 0
原创粉丝点击