Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shuffling a sorted array

If we are given an array that is sorted, what algorithm can we use to create an output array that has the same elements as the sorted array, but the elements should be randomly shuffled. I am looking for an algorithm that has a complexity of O(n)

like image 610
RagHaven Avatar asked Sep 06 '12 08:09

RagHaven


1 Answers

Collections.shuffle(List) has an O(n) time complexity. You can use Arrays.asList() to wrap the array so you can use this function.

What it does is;

For each element from the last to the second element, swap the element with a random element from the rest of the list which includes itself i.e. it could randomly not move an element.

for (int i=size; i>1; i--)
    swap(list, i-1, rnd.nextInt(i));
like image 124
Peter Lawrey Avatar answered Oct 05 '22 10:10

Peter Lawrey