import secrets
def is_sorted_desc(arr):
arr_len = len(arr)
if arr_len < 2: return True
i = 0
while i < (arr_len - 1):
if arr[i] < arr[i+1]: return False
i += 1
return True
def randomize(arr):
rnd = secrets.SystemRandom()
arr_len = len(arr)
sorted_arr = []
arr_cpy = arr.copy()
i = 0
while i < arr_len:
sorted_arr.append(arr_cpy.pop(rnd.randint(0, len(arr_cpy)-1)))
i += 1
return sorted_arr
def random_sort(arr, top_score):
sorted_arr = arr
counter = 0
while not is_sorted_desc(sorted_arr):
sorted_arr = randomize(arr)
counter += 1
print("Sorted after {0} tries!".format(counter))
return sorted_arr
score_list = [1, 2, 3, 9999, 13]
top = 10000
print(random_sort(score_list, top))
Ladies and gents, I present to you random_sort(). And yes , it does exactly what it sounds like. random_sort() takes an array as input, reassembles its elements in random order and checks if it’s sorted. If not: repeat.
Simple and beautiful. No other sorting algorithm can be explained this fast. And it works! At least, stochastic tells us it should always terminate eventually. Just don’t let the input arrays get too long if you’re an impatien person…