|
| 1 | +# For this problem generate a random list of 5 values between 1 and 9 |
| 2 | +import random |
| 3 | +num_list = [] |
| 4 | +for i in range(5): |
| 5 | + num_list.append(random.randrange(1, 9)) |
| 6 | + |
| 7 | +# Bubble Sort |
| 8 | + |
| 9 | +# The Bubble sort is a way to sort a list. It works this way : |
| 10 | +# 1. An outer loop decreases in size each time |
| 11 | +# 2. The goal is to have the largest number at the end of the list when the outer loop completes 1 cycle |
| 12 | +# 3. The inner loop starts comparing indexes at the beginning of the loop |
| 13 | +# 4. Check if list[Index] > list[Index + 1] |
| 14 | +# 5. If so swap the index values |
| 15 | +# 6. When the inner loop completes the largest number is at the end of the list |
| 16 | +# 7. Decrement the outer loop by 1 |
| 17 | + |
| 18 | +# Create the value that will decrement for the outer loop |
| 19 | +# Its value is the last index in the list |
| 20 | +i = len(num_list) - 1 |
| 21 | +while i > 1: |
| 22 | + j = 0 |
| 23 | + |
| 24 | + while j < i: |
| 25 | + # Tracks the comparison of index values |
| 26 | + print("\nIs {} > {}".format(num_list[j], num_list[j+1])) |
| 27 | + print() |
| 28 | + |
| 29 | + # If the value on the left is bigger switch values |
| 30 | + if num_list[j] > num_list[j+1]: |
| 31 | + print("Switch") |
| 32 | + |
| 33 | + temp = num_list[j] |
| 34 | + num_list[j] = num_list[j + 1] |
| 35 | + num_list[j + 1] = temp |
| 36 | + else: |
| 37 | + print("Don't Switch") |
| 38 | + |
| 39 | + j += 1 |
| 40 | + |
| 41 | + # Track changes to the list |
| 42 | + for k in num_list: |
| 43 | + print(k, end=", ") |
| 44 | + print() |
| 45 | + print("END OF ROUND") |
| 46 | + |
| 47 | + i -= 1 |
| 48 | + |
| 49 | +for k in num_list: |
| 50 | + print(k, end=", ") |
| 51 | +print() |
0 commit comments