- package com.eshore.sweetop.orderstatistic;
- import java.util.Random;
- public class RandomSelect {
- private static Random rd = new Random(47);
- public static int select(int[] a, int i) {
- return select(a, 0, a.length-1, i);
- }
- public static int select(int[] a, int p, int r, int i) {
- if(p==r){
- return a[p];
- }
- int q=randomPartition(a,p,r);
- int k=q-p+1;
- if(i==k){
- return a[q];
- }else if(i<k){
- return select(a,p,q-1,i);
- }else{
- return select(a,q+1,r,i-k);
- }
- }
- private static int randomPartition(int[] a, int p, int r) {
- int d = rd.nextInt(r - p) + p;
- a[d] ^= a[r];
- a[r] ^= a[d];
- a[d] ^= a[r];
- return partition(a, p, r);
- }
- private static int partition(int[] a, int p, int r) {
- int x = a[r];
- int i = p - 1;
- for (int j = p; j < r; j++) {
- if (a[j] < x) {
- i++;
- if (i != j) {
- a[i] ^= a[j];
- a[j] ^= a[i];
- a[i] ^= a[j];
- }
- }
- }
- if (i + 1 != r) {
- a[i + 1] ^= a[r];
- a[r] ^= a[i + 1];
- a[i + 1] ^= a[r];
- }
- return i + 1;
- }
- public static void main(String[] args) {
- int[] a={12,33,6,8,16,29,66};
- System.out.println(select(a,1));
- }
- }
算法-----线性顺序统计
最新推荐文章于 2016-04-01 15:01:54 发布