美文网首页
奇怪的知识1:🐒猴子排序

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

作者: Cat9527 | 来源:发表于2023-01-10 22:35 被阅读0次
    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;
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:奇怪的知识1:🐒猴子排序

          本文链接:https://www.haomeiwen.com/subject/xjxbcdtx.html