diff --git a/README.md b/README.md index 0ecb6ab..2d01d13 100644 --- a/README.md +++ b/README.md @@ -1 +1,18 @@ -# DataStructuresAlgorithmsVisualization \ No newline at end of file +# 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 diff --git a/__pycache__/sortingalgorithm.cpython-39.pyc b/__pycache__/sortingalgorithm.cpython-39.pyc new file mode 100644 index 0000000..b404a8d Binary files /dev/null and b/__pycache__/sortingalgorithm.cpython-39.pyc differ diff --git a/sortingalgorithm.py b/sortingalgorithm.py new file mode 100644 index 0000000..0d6c2b6 --- /dev/null +++ b/sortingalgorithm.py @@ -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]) \ No newline at end of file diff --git a/sortingvisualizationtool.py b/sortingvisualizationtool.py new file mode 100644 index 0000000..e74a987 --- /dev/null +++ b/sortingvisualizationtool.py @@ -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() \ No newline at end of file