Scribbling

Shuffle Algorithm: Knuth Shuffle 본문

Computer Science/Algorithms & Data Structures

Shuffle Algorithm: Knuth Shuffle

focalpoint 2022. 1. 15. 22:53

This post is about Knuth Shuffle, a shuffle algorithm.

- This algorithm allows random shuffle, giving all permuations of array equal likelihood.

- No need for additional arrays, so memory complexity is O(1).

- Time complexity is O(N)

 

Code is pretty simple as below.

To give all permuations of a particular array equal likelihood, all the number should have the same probability to be placed in a certain index.

So, while iterating all the indexes (i), choose a random index (j) in range [i, len(x)-1] and swap their values. Here, range of j should include i so that certain index's numbers can stay the same.

x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def shuffle(x):
    import random
    for i in range(0, len(x)-1):
        j = random.randint(i, len(x)-1)
        x[i], x[j] = x[j], x[i]

shuffle(x)
print(x)

 

 

'Computer Science > Algorithms & Data Structures' 카테고리의 다른 글

Monotonic Stack  (0) 2022.08.08
LeetCode: 839. Similar String Groups  (0) 2022.05.25
AVL Tree, Python Code  (0) 2022.01.07
Segment Tree, Python Implementation  (0) 2022.01.06
Priority Queue  (0) 2021.12.22