I want to generate a permutation of an array a
and I don't want to use utility functions such as java.util.Collections()
.
The permutations should be randomized and every permutation should be possible to occur - but there is no need for an equally distributed probability.
The following code achieves this - but at poor performance :
// array holding 1,...,n
// initialized somewhere else
int[] a = new int[N];
for (int i = 0; i < a.length ; i++) {
int r = (int) (Math.random() * (i+1));
swap(r,i,a);
}
private static void swap(int j, int k, int[] array){
int temp = array[k];
array[k] = array[j];
array[j] = temp;
}
Question:
Is there any chance of reducing the total number of random numbers used for the generation of a permutation?
I'll be surprised if anyone improves on the Knuth shuffle. It's O(n).
This citation claims an O(n log n) algorithm.
We'd all love to see see O(log n) or O(1).
O(log n) algorithms usually depend on "divide and conquer" bisection, which brings to mind cutting the deck and dividing each half.
But I can't help but think that if a faster algorithm were accessible Knuth would have found it.