1. 程式人生 > >中位數演算法-自己寫的爛碼

中位數演算法-自己寫的爛碼

import java.util.*;
public class Zhongweishufa {
    public static void main(String args[]){
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            int n=in.nextInt();
            double num[]=new double[n];
            for(int i=0;i<n;i++){
                num[i]=in.nextDouble();
            }
            System.out.println(Zhong(num,0,num.length-1));
        }
    }
    public static double Zhong(double num[],int first,int end) {
        double key = num[first];
        int i = first, j = end;
        while (i < j) {
            while (num[j] >=key && i<j)
                j--;
            while (num[i]<= key && i<j)
                i++;
            if(i<j){
                double temp=num[j];
                num[i]=num[j];
                num[j]=temp;
            }
        }
        num[first]=num[i];
        num[i]=key;
        //陣列長度為奇數時
        if(num.length%2==1){
            if(i==num.length/2){
                return num[i];
            }else{
                if(i>num.length/2){
                   return Zhong(num,first,i-1);
                }else{
                    return Zhong(num,i+1,end);
                }
            }
        }else{  // 陣列長度為偶數時
            if(i==num.length/2){
                return (num[i]+Max(num,first,i-1))/2;
            }else if(i==num.length/2-1){
                return (num[i]+Min(num,i+1,end))/2;
            }else{
                if(i<num.length/2){
                    return Zhong(num,i+1,end);
                }
                else{
                    return Zhong(num,first,i-2);
                }
            }
        }
    }
    //求出最大數
    public static double Max(double num[],int first,int end){
        double maxtemp=num[first];
        for(int i=first+1;i<=end;i++)
            if(maxtemp<num[i])
                maxtemp=num[i];
        return maxtemp;
    }
    //求出最小數
    public static double Min(double num[],int first,int end){
        double mintemp=num[first];
        for(int i=first+1;i<=end;i++)
            if(mintemp>num[i])
                mintemp=num[i];
        return mintemp;
    }
}