算法-----线性顺序统计

  1. package com.eshore.sweetop.orderstatistic;
  2. import java.util.Random;
  3. public class RandomSelect {
  4.     private static Random rd = new Random(47);
  5.     public static int select(int[] a, int i) {
  6.         return select(a, 0, a.length-1, i);
  7.     }
  8.     public static int select(int[] a, int p, int r, int i) {
  9.         if(p==r){
  10.             return a[p];
  11.         }
  12.         int q=randomPartition(a,p,r);
  13.         int k=q-p+1;
  14.         if(i==k){
  15.             return a[q];
  16.         }else if(i<k){
  17.             return select(a,p,q-1,i);
  18.         }else{
  19.             return select(a,q+1,r,i-k);
  20.         }
  21.     }
  22.     private static int randomPartition(int[] a, int p, int r) {
  23.         int d = rd.nextInt(r - p) + p;
  24.         a[d] ^= a[r];
  25.         a[r] ^= a[d];
  26.         a[d] ^= a[r];
  27.         return partition(a, p, r);
  28.     }
  29.     private static int partition(int[] a, int p, int r) {
  30.         int x = a[r];
  31.         int i = p - 1;
  32.         for (int j = p; j < r; j++) {
  33.             if (a[j] < x) {
  34.                 i++;
  35.                 if (i != j) {
  36.                     a[i] ^= a[j];
  37.                     a[j] ^= a[i];
  38.                     a[i] ^= a[j];
  39.                 }
  40.             }
  41.         }
  42.         if (i + 1 != r) {
  43.             a[i + 1] ^= a[r];
  44.             a[r] ^= a[i + 1];
  45.             a[i + 1] ^= a[r];
  46.         }
  47.         return i + 1;
  48.     }
  49.     
  50.     public static void main(String[] args) {
  51.         int[] a={12,33,6,8,16,29,66};
  52.         System.out.println(select(a,1));
  53.     }
  54. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值