Skip to content

Master #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,18 @@
# DataStructuresAlgorithmsVisualization
# DataStructuresAlgorithmsVisualization

Inspired from my course in Data Structures & Algorithms (i.e. sorting, graphs, heap)

Began brainstorming and implementing sorting algorithms utilized for class activities (Documentation also included)

# Beginning with sorting algorithms we learned first in-class which is inclusive of:
# Selection Sort ( Worst Case: O(n^2), Best: Ω(n^2) )
# Insertion Sort ( O(n^2), Ω(n) )
# Quick Sort ( O(n^2), Ω(n log(n)) )
# Merge Sort ( O(n log(n), Ω(n log(n)) )
# and more to come!

# Visualization tool created using Python to complement the sorting algorithmic construction file: See current work in progress above

Includes comments for each sorting algorithm in "sortingalgorithm.py" noting the time complexity and description of each

Runnable i.e. open sortingvisualizationtool in terminal then specify algorithm
Binary file added __pycache__/sortingalgorithm.cpython-39.pyc
Binary file not shown.
77 changes: 77 additions & 0 deletions sortingalgorithm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Sorting Algorithm Visualizer
# Inspired throughout my completion in our Data Structures and Algorithm's course during university

# Beginning with sorting algorithms we learned first in-class which is inclusive of:
# Selection Sort
# Insertion Sort
# Quick Sort
# Merge Sort
# and more to come!

# OOP based implementation

import random, time

class Algorithm:
def __init__(self, name):
# constructor
self.array = random.sample(range(512), 512)
# Builtin Python function
# returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement.
self.name = name

def refreshScreen(self, swap1=None, swap2=None):
import sorting_visualiser
sorting_visualiser.update(self, swap1, swap2)
# The update() method updates the dictionary with the elements from the another dictionary object or from an iterable of key/value pairs.

def run(self):
# runs the algorithm
self.start_time = time.time()
self.algorithm()
time_elapsed = time.time() - self.start_time
return self.array, time_elapsed

# Inspiration: https://www.youtube.com/watch?v=kFeXwkgnQ9U&ab_channel=DerrickSherrill
# https://www.geeksforgeeks.org/selection-sort/
# https://www.bigocheatsheet.com/
# https://en.wikipedia.org/wiki/Selection_sort
# "The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given array.
class SelectionSort(Algorithm):
def __init__(self):
super().__init__("SelectionSort")

def algorithm(self):
# traverse through all the elments in array
for i in range(len(self.array)):
# "Find the minimum element in remaining unsorted array"
min_idx = i
for j in range(i+1, len(self.array)):
if self.array[j] < self.array[min_idx]:
min_idx = j
# "Swap the found minimum element with the first element ""
self.array[i], self.array[min_idx] = self.array[min_idx], self.array[i]
# update screen
self.refreshScreen(self.array[i], self.array[min_idx])

# https://www.geeksforgeeks.org/insertion-sort/
# "Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
class InsertionSort(Algorithm):
def __init__(self):
super().__init__("InsertionSort")

def algorithm(self):
# traverse entire length of array
for i in range(len(self.array)):
cursor = self.array[i]
# "Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position"
idx = i
# set idx equal to i index
while idx > 0 and self.array[idx-1] > cursor:
self.array[idx] = self.array[idx-1]
idx -= 1
self.array[idx] = cursor
# represents the key in this case

# refresh screen
self.refreshScreen(self.array[idx], self.array[i])
101 changes: 101 additions & 0 deletions sortingvisualizationtool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# Sorting Algorithm Visualizer
# Inspired throughout my completion in our Data Structures and Algorithm's course during university

# Beginning with sorting algorithms we learned first in-class which is inclusive of:
# Selection Sort
# Insertion Sort
# Quick Sort
# Merge Sort
# and more to come!

# Visualization tool created using Python to complement the sorting algorithmic construction file: See current work in progress above
# Primarily for reference

import sortingalgorithm, time, os, sys
# https://docs.python.org/3/library/time.html
# https://www.geeksforgeeks.org/os-module-python-examples/ (important)
# https://www.python-course.eu/sys_module.php
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
# captures mapping, represents string environment
import pygame
# https://www.pygame.org/docs/ (custom effects, etc.)
# https://www.pygame.org/docs/tut/ImportInit.html
# https://docs.python.org/3/library/time.html

from pygame.locals import *
# imports the pygame module into the "pygame" namespace (saves typing)

# Inspiration: https://www.youtube.com/watch?v=kFeXwkgnQ9U&ab_channel=DerrickSherrill

dimensions = (1200, 600)
# able to change width, height
# warning: y value should fit array len

algorithms = {"SelectionSort": sorting_algorithms.SelectionSort(), \
"InsertionSort": sorting_algorithms.InsertionSort()}
# will add Merge, Heap, and Quick Sort in the near future
# https://www.geeksforgeeks.org/selection-sort/
# https://www.geeksforgeeks.org/insertion-sort/

if len(sys.argv) > 1:
if sys.argv[1] == "list":
for key in algorithms.keys(): print(key, end=" ")
# returns a view object
print("")
sys.exit(0)

pygame.init()
# safely initalizes all imported pygame modules
display = pygame.display.set_mode((dimensions[0], dimensions[1]))
# https://www.pygame.org/docs/ref/display.html
display.fill(pygame.Color("white"))

def checkIfQuit():
# check for quit event
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit(); sys.exit();

def refresh(algorithm, swap1=None, swap2=None, display=display):
display.fill(pygame.Color("white"))

pygame.display.set_caption("Sorting Visualization Tool Algorithm: {} Time: {:.3f} Status: Sorting".format(algorithm.name, time.time() - algorithm.start_time))
k = int(dimensions[0]/len(algorithm.array))

for i in range(len(algorithm.array)):
colour = (0,0,0)
if swap1 == algorithm.array[i]:
colour = (0,255,0)
elif swap2 == algorithm.array[i]:
colour = (255,0,0)
pygame.draw.rect(display, colour, (i*k,dimensions[1],k,-algorithm.array[i]))

checkIfQuit()
pygame.display.refresh()

def whileActive(algorithm, display, time):
pygame.display.set_caption("Sorting Visualization Tool Algorithm: {} Time: {:.3f} Status: Done".format(algorithm.name, time))

while True:
checkIfQuit()
pygame.display.refresh()

def main():
if len(sys.argv) < 2:
print("Exception: Please enter a sorting algorithm")
else:
try:
algorithm = algorithms[sys.argv[1]]
try:
time_elapsed = algorithm.run()[1]
whileActive(algorithm, display, time_elapsed)
pass
except:
pass
except:
# catch excepts
print("Exception: {} is not one of the valid sorting algorithms".format(sys.argv[1]))
print("Side Note: Sorting algorithms are in Camel Case format")

if __name__ == "__main__":
main()