Skip to content

Instantly share code, notes, and snippets.

@antonio-catalano
Last active April 24, 2018 12:33
Show Gist options
  • Save antonio-catalano/f88cbaabb815001a4967086d8699c9ed to your computer and use it in GitHub Desktop.
Save antonio-catalano/f88cbaabb815001a4967086d8699c9ed to your computer and use it in GitHub Desktop.
bubble sort quiz
''' In this link the description of problem: https://twitter.com/CutTheKnotMath/status/988401818915999744 '''
import random
def bubblesortOnePass(l):
if len(l) == 1:
return l
else:
for i in range(len(l)):
try:
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
except:
if l[-2] > l[-1]:
l[-2],l[-1] = l[-1],l[-2]
return l
def bubblesortTwoPass(l):
global counter
if len(l) == 1 or counter == 2:
return l
else:
for i in range(len(l)):
try:
if l[i] > l[i+1]:
l[i], l[i+1] = l[i+1], l[i]
except:
if l[-2] > l[-1]:
l[-2],l[-1] = l[-1],l[-2]
counter += 1
return bubblesortTwoPass(l[:-1]) + [l[-1]]
def generateList():
L = []
remaining = [i for i in range(1,41)]
while len(L) < 40:
random_N = random.choice(remaining)
L.append(random_N)
remaining.remove(random_N)
return L
N = 1000000
totalOnePass = 0
totalTwoPass = 0
for i in range(N):
L = generateList()
f = L[19]
K = L.copy()
bubblesortOnePass(L)
if f == L[29]:
totalOnePass += 1
counter = 0
After2pass = bubblesortTwoPass(K)
if f == After2pass[29]:
totalTwoPass += 1
print("Probability after One Pass is {}".format(float(totalOnePass / N)))
print("Probability after Two Pass is {}".format(float(totalTwoPass / N)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment