2019-09-07 13:20:07 +00:00
|
|
|
import PySimpleGUI as sg
|
|
|
|
import random
|
|
|
|
# ------- Sort visualizer. Displays bar chart representing list items -------
|
|
|
|
BAR_SPACING, BAR_WIDTH, EDGE_OFFSET = 11, 10, 3
|
2019-10-23 20:10:03 +00:00
|
|
|
DATA_SIZE = GRAPH_SIZE = (700, 500) # width, height of the graph portion
|
|
|
|
|
2019-09-07 13:20:07 +00:00
|
|
|
|
|
|
|
def bubble_sort(arr):
|
|
|
|
def swap(i, j):
|
|
|
|
arr[i], arr[j] = arr[j], arr[i]
|
|
|
|
n = len(arr)
|
|
|
|
swapped = True
|
|
|
|
x = -1
|
|
|
|
while swapped:
|
|
|
|
swapped = False
|
|
|
|
x = x + 1
|
|
|
|
for i in range(1, n - x):
|
|
|
|
if arr[i - 1] > arr[i]:
|
|
|
|
swap(i - 1, i)
|
|
|
|
swapped = True
|
|
|
|
yield arr
|
|
|
|
|
2019-10-23 20:10:03 +00:00
|
|
|
|
|
|
|
def draw_bars(graph, items):
|
2019-09-07 13:20:07 +00:00
|
|
|
# type: (sg.Graph, List)->None
|
|
|
|
for i, item in enumerate(items):
|
|
|
|
graph.draw_rectangle(top_left=(i * BAR_SPACING + EDGE_OFFSET, item),
|
2019-10-23 20:10:03 +00:00
|
|
|
bottom_right=(i * BAR_SPACING + EDGE_OFFSET + BAR_WIDTH, 0),
|
|
|
|
fill_color='#76506d')
|
|
|
|
|
2019-09-07 13:20:07 +00:00
|
|
|
|
|
|
|
def main():
|
2019-12-24 23:52:47 +00:00
|
|
|
sg.theme('LightGreen')
|
2019-09-07 13:20:07 +00:00
|
|
|
# Make list to sort
|
|
|
|
num_bars = DATA_SIZE[0]//(BAR_WIDTH+1)
|
2019-10-23 20:10:03 +00:00
|
|
|
list_to_sort = [DATA_SIZE[1]//num_bars*i for i in range(1, num_bars)]
|
2019-09-07 13:20:07 +00:00
|
|
|
random.shuffle(list_to_sort)
|
|
|
|
|
|
|
|
# define window layout
|
2019-10-23 20:10:03 +00:00
|
|
|
graph = sg.Graph(GRAPH_SIZE, (0, 0), DATA_SIZE)
|
2019-09-07 13:20:07 +00:00
|
|
|
layout = [[graph],
|
2019-10-23 20:10:03 +00:00
|
|
|
[sg.Text('Speed Faster'), sg.Slider((0, 20), orientation='h', default_value=10, key='-SPEED-'), sg.Text('Slower')]]
|
2019-09-07 13:20:07 +00:00
|
|
|
|
|
|
|
window = sg.Window('Sort Demonstration', layout, finalize=True)
|
2019-10-23 20:10:03 +00:00
|
|
|
# draw the initial window's bars
|
|
|
|
draw_bars(graph, list_to_sort)
|
2019-09-07 13:20:07 +00:00
|
|
|
|
|
|
|
sg.popup('Click OK to begin Bubblesort') # Wait for user to start it up
|
|
|
|
bsort = bubble_sort(list_to_sort) # get an iterator for the sort
|
2019-10-23 20:10:03 +00:00
|
|
|
timeout = 10 # start with 10ms delays between draws
|
2019-09-07 13:20:07 +00:00
|
|
|
while True: # ----- The event loop -----
|
|
|
|
event, values = window.read(timeout=timeout)
|
|
|
|
if event is None:
|
|
|
|
break
|
|
|
|
try:
|
|
|
|
partially_sorted_list = bsort.__next__()
|
|
|
|
except:
|
|
|
|
sg.popup('Sorting done!')
|
|
|
|
break
|
2019-10-23 20:10:03 +00:00
|
|
|
graph.erase()
|
2019-09-07 13:20:07 +00:00
|
|
|
draw_bars(graph, partially_sorted_list)
|
|
|
|
timeout = int(values['-SPEED-'])
|
2019-10-23 20:10:03 +00:00
|
|
|
|
2019-09-07 13:20:07 +00:00
|
|
|
window.close()
|
2019-10-23 20:10:03 +00:00
|
|
|
|
|
|
|
|
|
|
|
main()
|