Last active
April 24, 2018 12:33
-
-
Save antonio-catalano/f88cbaabb815001a4967086d8699c9ed to your computer and use it in GitHub Desktop.
bubble sort quiz
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
''' 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