众数问题:给定含有N个元素的多重集合S,每个元素在S中出现的次数称为该元素的重数,多重集合S中重数最大的元素称为多重集合S的众数,众数的重数称为多重集合S的重数,试求一个给定多重结合的重数和众数;
package zongshu;
public class Serach {
static int number=0;
static int sum=0;
int Partition(int a[],int p,int r){
int x=a[r];
int i=p-1;
int temp,j;
for(j=p;j<=r-1;j++)
{
if(a[j]<=x)
{
i++;
temp=a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp=a[i+1];
a[i+1]=a[r];a[r]=temp;
return i+1;
}
int Count(int a[],int x,int p,int r)
{
int count=0,i;
for(i=p;i<=r;i++)
{
if(a[i]==x)
count++;
}
return count;
}
void Modal(int a[],int p,int r)
{
if(p<r)
{
int q=Partition(a,p,r);
int temp=Count(a,a[q],p,q);
if(sum<temp)
{
sum=temp;
number=a[q];
}
Modal(a,p,q-1);
Modal(a,q+1,r);
}
}
public static void main(String[] args)
{
int[] num={4,3,2,2,7,2,4,5};
Serach s1=new Serach();
s1.Modal(num,0,num.length-1);
System.out.println("该集合众数是:"+number);
System.out.println("该集合重数是:"+sum);
}
}
转载于:https://blog.51cto.com/13271983/2046370