|
| 1 | +import colorama |
| 2 | + |
| 3 | +CLEAR_SCREEN = '\u001b[2J' |
| 4 | +START_OF_LINE = '\u001b[1G' |
| 5 | +CLEAR_LINE = f'{START_OF_LINE}\u001b[0K' |
| 6 | +PREVIOUS_LINE = colorama.Cursor.UP(1) |
| 7 | +HIDE_CURSOR = '\u001b[?25l' |
| 8 | + |
| 9 | + |
| 10 | +def format_data(data, position=None): |
| 11 | + result = "[ " |
| 12 | + inverse = False |
| 13 | + for index, val in enumerate(data): |
| 14 | + if (position is not None) and (position == index): |
| 15 | + result += colorama.Back.LIGHTYELLOW_EX |
| 16 | + inverse = True |
| 17 | + result += f"{val}" |
| 18 | + if (position is not None) and (index == position + 1) and inverse: |
| 19 | + result += colorama.Back.RESET |
| 20 | + inverse = False |
| 21 | + result += " " |
| 22 | + |
| 23 | + result += "]" |
| 24 | + return result |
| 25 | + |
| 26 | + |
| 27 | +def bubble_sort(data: list) -> None: |
| 28 | + """Sorts a list in place.""" |
| 29 | + n = len(data) |
| 30 | + comparison_count = 0 |
| 31 | + |
| 32 | + for i in range(n - 1): |
| 33 | + print(f"i = {i}. Starting inner loop with {format_data(data)}") |
| 34 | + print(end="") |
| 35 | + for j in range(n - 1 - i): |
| 36 | + print(f"{CLEAR_LINE}j = {j}, {format_data(data, j)}", end="") |
| 37 | + comparison_count += 1 |
| 38 | + if data[j] > data[j + 1]: |
| 39 | + print(f"\t{colorama.Fore.RED}" |
| 40 | + f"Swapping {data[j]} and {data[j + 1]}" |
| 41 | + f"{colorama.Fore.RESET}", end="") |
| 42 | + data[j], data[j + 1] = data[j + 1], data[j] |
| 43 | + input(f"{PREVIOUS_LINE}") |
| 44 | + print(f"{CLEAR_LINE}j = {j}, {format_data(data, j)}", end="") |
| 45 | + |
| 46 | + # Pause |
| 47 | + input(f"{PREVIOUS_LINE}") |
| 48 | + |
| 49 | + print(f"End of pass {i}. `data` is now {format_data(data)}") |
| 50 | + print(f"comparison_count is {comparison_count}") |
| 51 | + |
| 52 | + |
| 53 | +colorama.init() |
| 54 | + |
| 55 | +numbers = [3, 2, 4, 1, 5, 7, 6] |
| 56 | +# numbers = [7, 6, 5, 4, 3, 2, 1] |
| 57 | + |
| 58 | +print(f"{CLEAR_SCREEN}{HIDE_CURSOR}Sorting {format_data(numbers)}") |
| 59 | +bubble_sort(numbers) |
| 60 | +print(f"The sorted data is {format_data(numbers)}") |
| 61 | + |
| 62 | +colorama.deinit() |
0 commit comments