奇怪的知识1:🐒猴子排序

public class BogoSortExample {
    public static void main(String[] args) {
        int[] sorted = {1, 1, 2, 3, 4, 4, 6, 7, 8};
        int[] array = {2, 1, 1, 3, 6, 4, 4, 7, 8};
        bogoSort(array);
        assert Arrays.equals(sorted, array);
    }

    /**
     * Sorts the specified array into ascending numerical order.
     *
     * @param array the array to be sorted.
     */
    public static void bogoSort(int[] array) {
        while (!isSorted(array)) {
            shuffle(array);
        }
    }

    /**
     * Returns {@code true} if the specified array is in ascending numerical order
     * otherwise returns {@code false}.
     *
     * @param array the array to be checked for ascending numerical order.
     * @return {@code true} if the specified array is in ascending numerical order
     * otherwise {@code false}.
     */
    public static boolean isSorted(int[] array) {
        for (int i = 0; i < array.length - 1; i++) {
            if (array[i] > array[i + 1]) {
                return false;
            }
        }
        return true;
    }

    /**
     * Randomly permutes the specified array using a default source of randomness.
     * All permutations occur with approximately equal likelihood.
     *
     * @param array the array to be shuffled.
     */
    public static void shuffle(int[] array) {
        Random r = random;
        if (r == null) {
            random = r = new Random();
        }
        shuffle(array, r);
    }

    private static Random random;

    /**
     * Randomly permutes the specified array using the specified source of randomness.
     * All permutations occur with equal likelihood assuming that the source of
     * randomness is fair.
     *
     * @param array  the array to be shuffled.
     * @param random the source of randomness to use to shuffle the array.
     */
    public static void shuffle(int[] array, Random random) {
        for (int i = array.length - 1; i > 0; i--) {
            int j = random.nextInt(i + 1);
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容