LinkedIn interview question

randomize an array.

Interview Answers

Anonymous

23 Jun 2011

Use the Knuth shuffle: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Anonymous

4 Jul 2010

To perform perfect randomization of an array of elements there is a well known method (all n! permutations of the array are equally probable assuming a perfect random number generator) public static void randomize(int[] a) { int tmp, index; for (int i = 0; i < a.length; i++){ index = (int) (Math.random() * (a.length - i)) + i; tmp= a[i]; a[i] = a[index]; a[index] = tmp; } }

1