It's possible to conceive of a modification to bubble sort where the "swap" occurs randomly with probability p
, rather than by performing a comparison. The result could be called a "bubble shuffle". Elements near the front would be likely to remain there, but have a chance to be shifted to the back of the list.
Modifying a bubble sort stolen from the internet you could come up with the following:
import random
def bubble_shuffle(arr, p):
arr = copy.copy(arr)
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if random number [0, 1] is less than p
if random.random() < p:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
This algorithm is order n-squared... but the probability of an element ending up in any particular spot should be computable ahead of time, so it doesn't "need" to be n-squared. Is there a more efficient approach which could be taken?
I'd considered sampling from a geometric distribution and add this to the original index (plus (len(n)-i-1)/len(n)
to break ties), but this doesn't give the same dynamic.
from Bubble Shuffle - Weighted Shuffle
No comments:
Post a Comment