洗牌算法

洗牌算法是将原来的数组进行打散,使原数组的某个数在打散后的数组中的每个位置上等概率的出现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import random

def shuffle(arr):
l = len(arr)
for i in range(0, l):
# 从剩下的数中随机选择一个数与arr[i]交换
# 每个数被选中的概率为1/(l-i)
x = random.randint(i, l-1)
# 交换arr[i]和arr[x]
t = arr[x]
arr[x]=arr[i]
arr[i]=t
print("{}:{}".format(i, arr))
return arr

if __name__ == "__main__":
'''main'''
arr = [1,2,3,4,5,6,7,8,9,10]
shuffle(arr)
print(arr)

输出:

1
2
3
4
5
6
7
8
9
10
11
0:[10, 2, 3, 4, 5, 6, 7, 8, 9, 1]
1:[10, 9, 3, 4, 5, 6, 7, 8, 2, 1]
2:[10, 9, 7, 4, 5, 6, 3, 8, 2, 1]
3:[10, 9, 7, 4, 5, 6, 3, 8, 2, 1]
4:[10, 9, 7, 4, 1, 6, 3, 8, 2, 5]
5:[10, 9, 7, 4, 1, 6, 3, 8, 2, 5]
6:[10, 9, 7, 4, 1, 6, 2, 8, 3, 5]
7:[10, 9, 7, 4, 1, 6, 2, 3, 8, 5]
8:[10, 9, 7, 4, 1, 6, 2, 3, 5, 8]
9:[10, 9, 7, 4, 1, 6, 2, 3, 5, 8]
[10, 9, 7, 4, 1, 6, 2, 3, 5, 8]