Python Forum
Bubble sort quiz: why the result is not the same?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Bubble sort quiz: why the result is not the same?
#7
Your code seems a little complicated, but I agree with your answers.

For 1,000,000 passes I got the following results using my code:
Output:
Pass 1 1090 counts Frequency 0.00109 Pass 2 2042 counts Frequency 0.00204
You do not need two algorithms. You could use something like:
import random
 
def bubble_sort_one_pass(a, pass_number):
    n = len(a)
 
    # Subtract 1 because arrays are '0 based' and Pass 1 uses index 0
    i = pass_number - 1
    for j in range(0, n-i-1):
        if a[j] > a[j+1] :
            a[j], a[j+1] = a[j+1], a[j]
    return(a)

    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]

    pass_number = 1
    L = bubble_sort_one_pass(L, pass_number)
    if f == L[29]:
        totalOnePass += 1

    pass_number = 2
    L = bubble_sort_one_pass(L, pass_number)
    if f == L[29]:
        totalTwoPass += 1
print("Probability after One Pass is {}".format(float(totalOnePass / N)))
print("Probability after Two Pass is {}".format(float(totalTwoPass / N))) 
Lewis
To paraphrase: 'Throw out your dead' code. https://www.youtube.com/watch?v=grbSQ6O6kbs Forward to 1:00
Reply


Messages In This Thread
RE: Bubble sort quiz: why the result is not the same? - by ljmetzger - Apr-25-2018, 01:44 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  QUIZ GUI Form_When admin panel is open, main quiz form is getting freeze Uday 4 887 Aug-25-2023, 08:24 PM
Last Post: deanhystad
Photo a.sort() == b.sort() all the time 3lnyn0 1 1,430 Apr-19-2022, 06:50 PM
Last Post: Gribouillis
  Python Networkx: Visualize an edge weight with a bubble/circle uvw 0 2,111 Sep-01-2021, 06:26 AM
Last Post: uvw
  Bubble sort on randomized integers bellevie 4 5,543 May-16-2017, 05:28 PM
Last Post: bellevie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020