Visualizing Bubble Sort using Tkinter in Python
In this article, we will use the Python GUI Library Tkinter to visualize the Bubble Sort algorithm.
- Tkinter is a very easy to use and beginner-friendly GUI library that can be used to visualize the sorting algorithms.
- Here Bubble Sort Algorithm is visualized which works by repeatedly swapping the adjacent elements/values if they are in the wrong order until the whole array is sorted.
- The idea is that : if arr[i] > arr[i+1] then swap them.
- In the first iteration, N-1 items have to be scanned and the largest element moves to its right position. In the second iteration, the second largest item will move to its correct position, and after the third iteration (stopping at item N-3) the third largest will be in place. Therefore, to place all the elements in the correct order the above operation is performed N-1 times. This algorithm has Time Complexity = O(N2).
- A list of random values within a specified range is generated as bars.
- Different colors (red and green) are used to show the sorting process.
- A suitable “Speed” range bar is created for the ease of the user to visualize.
- “Generate” and “Start” buttons are created separately for the creation of data bars and initiation of the sorting process.
Extension Code for Bubble Sort :
This is the extension code for the bubble sort algorithm which is imported in the main Tkinter visualizer code to implement the bubble sort algorithm and return the sorted result.
Code for Tkinter :
In this code, we are generating the data values as bars of different lengths and a particular color. The basic layout is designed in a Tkinter ‘Frame’ and the portion when the bars are generated and the algorithm is visualized is designed in a Tkinter ‘Canvas’.
The code essentially has the following components:
- Mainframe: a Tkinter frame to arrange all the necessary components(labels, buttons, speed bar, etc.) in an organized manner
- Canvas: A Tkinter canvas used as the space where the generated data bars are drawn and the sorting process is visualized
- generate(): Method to generate the data values by accepting a range and then passing that as a parameter to the drawData() function
- drawData(): Method to generate bars to normalized data values(within the given range) of a particular color on the canvas
- start_algorithm(): This function is called when the “START” button is pressed. It initiates the sorting process by calling the bubble() function from the Bubble Sort Extension Code.
My Personal Notes arrow_drop_up
Please Login to comment...