Below I will give my implementation of random sort that you may find interesting :D
import random
def is_sorted(l):
length = len(l)
for i in range(length):
if i == length-1:
return True
elif (l[i] < l[i+1] or l[i] == l[i+1]):
continue
else:
return False
def rand(l):
length = len(l)
if is_sorted(l):
return l
else:
dic = {key:True for key in l}
count = 0
l2 = []
while True:
if count == length:
break
else:
ran = random.randint(0,length-1)
if dic[l[ran]]:
l2.append(l[ran-1])
count += 1
dic[l[ran]] = False
return rand(l2)
It is kind of exciting when you think that the best case runtime of this algorithm is better than any other, while the worst case is probably the worst.
Very insightful
ReplyDelete