标签:exti ret next 排序 new 数组 ext dom 平均情况
原理很简单,如果数组不是有序的,就洗一次牌,直至数组有序为止
最佳情况O(n),平均情况O(n×n!)
代码如下:
1 import java.util.Random; 2 3 public class QuantumBogo { 4 private static Random random = new Random(); 5 6 public static void sort(Comparable[] a){ 7 // int count = 0; 8 while (!isOrder(a)) { 9 shuffle(a); 10 // count++; 11 } 12 } 13 14 private static boolean isOrder(Comparable[] a){ 15 for (int i = 1; i < a.length; i++) { 16 if (a[i-1].compareTo(a[i]) > 0) 17 return false; 18 } 19 return true; 20 } 21 22 private static void shuffle(Comparable[] a){ 23 int n = a.length; 24 for (int i = 0; i < n; i++) { 25 int r = i + random.nextInt(n-i); 26 Comparable temp = a[i]; 27 a[i] = a[r]; 28 a[r] = temp; 29 } 30 } 31 32 private static void show(Comparable[] a){ 33 for (int i = 0; i < a.length; i++) 34 System.out.print(a[i] + " "); 35 System.out.println(); 36 } 37 38 public static void main(String[] args){ 39 Integer[] a = new Integer[12]; 40 for (int i = 0; i < 12; i++) { 41 a[i] = random.nextInt(65536); 42 } 43 show(a); 44 sort(a); 45 show(a); 46 } 47 }
标签:exti ret next 排序 new 数组 ext dom 平均情况
原文地址:https://www.cnblogs.com/merryituxz/p/9932431.html