|
| 1 | +public static void bogoSort(int length, int range) { |
| 2 | + int []array = randomIntArray(length,range); |
| 3 | + |
| 4 | + while (! isSorted(array)) |
| 5 | + array = randomArray(array); |
| 6 | + |
| 7 | + for (int i = 0; i < array.length; i++) { |
| 8 | + System.out.print(array[i] + " "); |
| 9 | + } |
| 10 | + |
| 11 | +} |
| 12 | + |
| 13 | +private static boolean isSorted(int [] array) |
| 14 | +{ |
| 15 | + for (int i = 0; i < (array.length - 1); ++i) { |
| 16 | + if (array[i] > array[i+1]) |
| 17 | + return false; |
| 18 | + } |
| 19 | + |
| 20 | + return true; |
| 21 | +} |
| 22 | + |
| 23 | +private static int [] randomArray(int [] array) { |
| 24 | + |
| 25 | + int size = array.length; |
| 26 | + int[] indices = new int[size]; |
| 27 | + for (int i=0; i<size; i++) { |
| 28 | + indices[i] = i; |
| 29 | + } |
| 30 | + |
| 31 | + Random random = new Random(); |
| 32 | + for (int i = 0; i < size; i++) { |
| 33 | + boolean unique = false; |
| 34 | + int nRandom = 0; |
| 35 | + while (!unique) { |
| 36 | + unique = true; |
| 37 | + nRandom = random.nextInt(size); |
| 38 | + for (int j = 0; j < i; j++) { |
| 39 | + if (indices[j] == nRandom) { |
| 40 | + unique = false; |
| 41 | + break; |
| 42 | + } |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + indices[i] = nRandom; |
| 47 | + } |
| 48 | + |
| 49 | + int [] result = new int[size]; |
| 50 | + for (int k = 0; k < size; k++) { |
| 51 | + result[indices[k]] = array[k]; |
| 52 | + } |
| 53 | + |
| 54 | + return result; |
| 55 | +} |
| 56 | + |
| 57 | +private static int[] randomIntArray(int length, int n) |
| 58 | +{ |
| 59 | + int[] a = new int[length]; |
| 60 | + Random generator = new Random(); |
| 61 | + for (int i = 0; i < a.length; i++) |
| 62 | + { |
| 63 | + a[i] = generator.nextInt(n); |
| 64 | + } |
| 65 | + return a; |
| 66 | +} |
0 commit comments