利用快速排序的子程序查找中位数

package net.liuyx.algorithm;

import java.util.Random;

public class QuickSelect {
    public static void main(String[] args) {
        int[] a = generateRandomArray();
        QuickSort.quickSort(a, 0, a.length - 1);
        arrayToString(a);
        System.out.println();
        int find = randomSelect(a, 0, a.length - 1, 3);
        System.out.println(find);
    }

    static int[] generateRandomArray() {
        Random rand = new Random();
        int[] b = new int[rand.nextInt(100)];
        for (int i = 0; i < b.length; i++)
            b[i] = rand.nextInt(100);
        return b;
    }

    static void arrayToString(int[] b) {
        for (int i : b) {
            System.out.print(i + " ");
        }
    }

    private static int randomSelect(int[] a, int p, int r, int theIthMin) {// theIthMin即第i小值,如i等于0,即为最小值,i等于1,即为第二小值,依次类推,i等于a.length-1,即为最大值
        if (p == r)
            return a[p];
        else if (p < r) {
            int q = QuickSort.randomPartition(a, p, r);
            if (theIthMin == q)
                return a[q];
            else if (theIthMin < q)
                return randomSelect(a, p, q - 1, theIthMin);
            else
                return randomSelect(a, q + 1, r, theIthMin);
        } else
             throw new RuntimeException("请确认起始位置p小于等于终止位置q");
    }

}

你可能感兴趣的:(String,Random,Class)