package decreaseAndConquer; /* * 找出一个n个数列的中间值 * 输入:一个整数数组n[0..n-1] * 输出:数列的中间值 */ public class MedianProblem { static int median(int arr[],int l,int r){ int k = (l+r)/2; int s = partition(arr,l,r); if(s==k){ return arr[k]; } else if(s<k){ return median(arr,k+1,arr.length-1); } else{ return median(arr,0,k-1); } } static int partition(int A[],int l,int r){ int p = A[l];//以第一个元素为中轴 int i = l+1; int j = r; int temp; while(i<j){ while(A[i]<=p&&i<r)i++; while(p<=A[j]&&j>l)j--; if(i<j){//第一种情况,扫描指针不相交,简单地交换A[i]和A[j] temp = A[j]; A[j] = A[i]; A[i] = temp; } }//第二种情况,扫描指针i>=j,交换中轴p与A[j]的位置 if(A[j]<A[l]){//这一判断条件很重要 temp = A[j]; A[j] = A[l]; A[l] = temp; } return j; } public static void main(String[] args) { int arr[] = {34,56,23,6,8,12,61,36,30,41,76,29,80}; System.out.println("中间值为:"+median(arr,0,arr.length-1)); } }