Finding the median in java without sorting [closed]

余生长醉 提交于 2019-12-31 02:45:10

问题


I need to write a program in java to find the median of an array of three or more integers without sorting. I need some ideas. thanks


回答1:


You can use a Selection Algorithm. You'll also find relevant information looking for Median of Medians.




回答2:


You can use Quick sort partitioning step with random pivots, without sorting it.

public class TestMedian {

    public static void main(String[] args){ 
        int[] a = {1,9,-4,7,6,11,3,2,10}; 
        int median; 

        median = new Median().findMedian(a,0,a.length-1); 
        if(a.length%2 != 0) 
            System.out.print("the median is : "+a[median]); 
        else 
            System.out.print("the median is : "+(a[median] + a[median + 1])/2 ); 
    } 
    public int findMedian(int[] a,int left,int right){ 
        int index = 0; 
        int mid = (left+right)/2; 
        index = partition(a,left,right); 
        while( index != mid){ 
            if(index < mid) 
                index = partition(a,mid,right); 
            else index = partition(a,left,mid); 
        } 
        return index; 
    } 
    public int partition(int[] a,int i,int j ){ 
        int pivot = (i+j)/2; 
        int temp; 
        while(i <= j){ 
            while(a[i] < a[pivot]) 
                i++; 
            while(a[j] > a[pivot]) 
                j--; 
            if(i <= j){ 
                temp = a[i]; 
                a[i]=a[j]; 
                a[j] = temp; 
                i++;j--; 
            } 
        } 
        return pivot; 
    } 

}


来源:https://stackoverflow.com/questions/22096554/finding-the-median-in-java-without-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!