随机排列数组:
一个通常的方法是为数组的每个元素A[i]赋一个随机的优先级P[i],然后依据优先级对数组A中的元素进行排序
Permute-by-sorting:
import random
def random_array(n):
P = random.sample(range(n*10), n)
return P
def permute_by_sorting(A):
n = len(A)
P = random_array(n)
print(P)
for j in range(n):
key_p = P[j]
key_a = A[j]
i = j-1
while i >= 0 and P[i] > key_p:
P[i+1] = P[i]
A[i+1] = A[i]
i-=1
P[i+1] = key_p
A[i+1] = key_a
return A
原理:给定列表长度n,生成n个不重复的在(0~10×n)之间的随机数,赋值给列表P。
permute_by_sorting方法的原理和插入排序差不多。比如A=[11,4,3,7],P=[17,20,24,6]。P代表什么意思呢?
运行:
>>> A = permute_by_sorting([1,2,3,4])
[17, 20, 24, 6]#随机数组P
>>> A
[4, 1, 2, 3]
>>>
另外一种方法:在进行第i此迭代是,元素A[i]是从元素A[i]到A[n]中随机选取的。第i次迭代之后,A[i]不再改变。
def randomize_in_place(A):
n = len(A)
for i in range(n):
j = random.randint(i,n-1)
key = A[i]
A[i] = A[j]
A[j] = key
return A