## 无序数组的中位数

 1 public　void　sort(int　arr[],int　low,int　high)
2 {
3     int　l=low;
4     int　h=high;
5     int　povit=arr[low];
6
7     while(l<h)
8     {
9         while(l<h&&arr[h]>=povit) h--;
10         if(l<h){
11             int　temp=arr[h];
12             arr[h]=arr[l];
13             arr[l]=temp;
14             l++;
15         }
16
17         while(l<h&&arr[l]<=povit) l++;
18
19         if(l<h){
20             int　temp=arr[h];
21             arr[h]=arr[l];
22             arr[l]=temp;
23             h--;
24         }
25     }
26
27     if(l>low) sort(arr,low,l-1);
28     if(l<high) sort(arr,l+1,high);
29 }

 1 public static double median2(int[] array){
2     if(array==null || array.length==0) return 0;
3     int left = 0;
4     int right = array.length-1;
5     int midIndex = right >> 1;
6     int index = -1;
7     while(index != midIndex){
8         index = partition(array, left, right);
9         if(index < midIndex) left = index + 1;
10         else if (index > midIndex) right = index - 1;
11         else break;
12     }
13     return array[index];
14 }
15
16 public static int partition(int[] array, int left, int right){
17     if(left > right) return -1;
18     int pos = right;
19     right--;
20     while(left <= right){
21         while(left<pos && array[left]<=array[pos]) left++;
22         while(right>left && array[right]>array[pos]) right--;
23         if(left >= right) break;
24         swap(array, left, right);
25     }
26
27     swap(array, left, pos);
28     return left;
29 }

 1 public static double median(int[] array){
2     int heapSize = array.length/2 + 1;
3     PriorityQueue<Integer> heap = new PriorityQueue<>(heapSize);
4     for(int i=0; i<heapSize; i++){
6     }
7     for(int i=heapSize; i<array.length; i++){
8         if(heap.peek()<array[i]){
9             heap.poll();
11         }
12     }
13     if(array.length % 2 == 1){
14         return (double)heap.peek();
15     }
16     else{
17         return (double)(heap.poll()+heap.peek())/2.0;
18     }
19 }

posted on 2016-08-07 14:56  _dshizhh  阅读(29548)  评论(2编辑  收藏  举报