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)
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With