Given an integer array, in-place shuffle it. The algorithm should produce an unbiased permutation, i.e., every permutation is equally likely.

Practice this problem

Fisher–Yates shuffle is an algorithm to generate random permutations. It takes time proportional to the total number of items being shuffled and shuffles them in place. The algorithm swaps the element at each iteration at random among all remaining unvisited indices, including the element itself.

Here’s the complete algorithm:

— To shuffle an array ‘a’ of ‘n’ elements:
for i from n-1 down to 1 do
    j = random integer such that 0 <= j <= i
    exchange a[j] and a[i]

Following is the implementation of the above algorithm in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

The time complexity of the above solution is O(n) and doesn’t require any extra space, where n is the size of the input. An equivalent version that shuffles the array in the opposite direction (from the lowest index to the highest) is:

— To shuffle an array ‘a’ of ‘n’ elements:
for i from 0 to n-2 do
    j = random integer such that i <= j < n
    exchange a[i] and a[j]

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

The time complexity of the above solution is O(n) and doesn’t require any extra space.

 
Exercise:

Modify the code to generate random cyclic permutations of length n instead of random permutations (Sattolo’s algorithm).

 
Reference: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle