分治算法求众数,重数问题java实现

public class Dvide_and_conquer_algorithm_multiplicity {

    /**
     * 1.先找到这一组的中位数,假设它就是众数,计算它的个数
     * 2.根据中位数的位置划分左边和右边,分成n个子问题,个数小于中位数个数的不必计算,中位数就是众数
     * 3.每次分割后继续比较
     */
    private static int multipleNumbers=0;//重数
    private static String mode;//众数
    private static int medianNumber;//中位数
    private static String [] element={"1","2","2","4","4","2","2","2","1","1","2"};
    private static void a(int start,int end){
        int mid=(start+end)/2;
        for(int i=start;imultipleNumbers){
                    multipleNumbers=medianNumber;
                    mode=element[mid];
                }
            }
        }
        if(mid>medianNumber){
            medianNumber=0;
            a(0,mid);
        }
        if(end-mid-1>medianNumber){
            medianNumber=0;
            a(mid+1,end);
        }

    }
    public static void main(String[] args) {

           a(0,element.length);
        System.out.println("重数: "+multipleNumbers+" 众数:"+mode);
    }
}

分治算法求众数,重数问题java实现_第1张图片

你可能感兴趣的:(众数问题)