import pygame
-
pygame.init()
+pygame.display.set_caption("sorting visuals")
+
BLACK = (0, 0, 0)
GRAY = (128, 128, 128)
WHITE = (255, 255, 255)
class Display:
- WIDTH, HEIGHT = 640, 640
+ WIDTH, HEIGHT = 1080, 720
DIMENSIONS = (WIDTH, HEIGHT)
- FPS = 60
+ FPS = 0
+
+ DELAY_TIME = 0
- def __init__(self):
+ def __init__(self, frames):
self.screen = pygame.display.set_mode(self.DIMENSIONS)
self.clock = pygame.time.Clock()
+ self.frames = frames
+ self.index = 0
+ self.time = 0
+
def show(self):
is_running = True
def update(self):
delta = self.clock.tick(self.FPS)
+ self.time += delta
+ if self.time > self.DELAY_TIME:
+ self.time = 0
+ self.index = min(len(self.frames) - 1, self.index + 1)
def draw(self, surf):
- surf.fill(GRAY)
+ surf.fill(WHITE)
+
+ width = self.WIDTH / len(self.frames[self.index])
+ height = self.HEIGHT / max(self.frames[self.index])
+
+ for i, element in enumerate(self.frames[self.index]):
+ r = pygame.Rect(i * width, self.HEIGHT - element * height + 1, width + 1, element * height)
+ pygame.draw.rect(surf, BLACK, r)
+import random
from display import Display
-
+from sorting_algorithms.bubble_sort import bubble_sort, bubble_sort_frames
def main():
- window = Display()
+ array = [random.randint(10, 50) for _ in range(75)]
+ frames = bubble_sort_frames(array)
+ window = Display(frames)
window.show()
# Bubble Sort (O(n^2))
-from utils import swap
+from sorting_algorithms.utils import swap
def bubble_sort(array):
if is_sorted: # break out if already sorted
break
return array # return sorted array
+def bubble_sort_frames(array):
+ frames = []
+ for top in range(len(array) - 1, 0, -1): # loop through each element from end
+ is_sorted = True # to end early if already sorted
+ for index in range(top): # loop through each of elements until reach top
+ if array[index] > array[index + 1]: # if greater, swap
+ swap(array, index, index + 1) # swap with next
+ is_sorted = False # reset to not sorted
+ frames.append(array[:])
+ if is_sorted: # break out if already sorted
+ break
+ return frames # return sorted array