In this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization.Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the array into two parts one sorted and the other unsorted part. Initially, the unsorted part contains all the elements and the sorted part is empty. In each iteration, we look for the minimum element in the unsorted part and swap it with the first element of the unsorted part and then we move the boundary of the sorted and unsorted parts one element to the right.
Selection sort visualizer using PyGame
We will be usingPyGame, aPython library for game development. In the visualizer, there will be an array as a row of bars with varying heights and we will also use colors to differentiate between sorted and unsorted parts of the array.z
Necessary modules
pip install pygame
Steps for Selection Sort Visualizer in Pygame
Setting the Window Screen
First, we need toset up the PyGame environment and will create a window with a black background.
Python3importpygameimportrandom# Initialize PyGamepygame.init()# Set up the windowwin_width=1280win_height=720win=pygame.display.set_mode((win_width,win_height))pygame.display.set_caption("Selection Sort Visualizer GeekforGeeks")win.fill((0,0,0))
Initialize the Sorted and Unsorted Part
Next, we need to generate a random array of integers and initialize the sorted and unsorted parts of the array
Python3# Generate random arrayarr_len=50arr=[random.randint(1,win_height)foriinrange(arr_len)]# Initialize sorted and unsorted parts of arraysorted_idx=-1unsorted_idx=0
Sorting Array Data
Now, we can create a loop that will iterate until the entire array is sorted
Python3# Selection sort loopwhilesorted_idx<arr_len-1:min_idx=unsorted_idxforiinrange(unsorted_idx,arr_len):ifarr[i]<arr[min_idx]:min_idx=iarr[unsorted_idx],arr[min_idx]=arr[min_idx],arr[unsorted_idx]sorted_idx=unsorted_idxunsorted_idx+=1# Draw barswin.fill((0,0,0))foriinrange(arr_len):color=(255,255,255)ifi<=sorted_idxelse(255,0,0)pygame.draw.rect(win,color,(i*(win_width/arr_len),win_height-arr[i],win_width/arr_len,arr[i]))pygame.display.update()
Handle Exit of Code
Finally, we need to add some event handling to exit the program.
Python3# Event handling looprunning=Truewhilerunning:foreventinpygame.event.get():ifevent.type==pygame.QUIT:running=False# Quit PyGamepygame.quit()
Complete Code
Overall, your code will look something like this
Python3importpygameimportrandom# Initializing PyGamepygame.init()# Set up the windowwin_width=1280win_height=720win=pygame.display.set_mode((win_width,win_height))pygame.display.set_caption("Selection Sort Visualizer GeekforGeeks")win.fill((0,0,0))# Generating random arrayarr_len=50arr=[random.randint(1,win_height)foriinrange(arr_len)]# Initializing sorted and unsorted parts of arraysorted_idx=-1unsorted_idx=0# Selection sort loopwhilesorted_idx<arr_len-1:min_idx=unsorted_idxforiinrange(unsorted_idx,arr_len):ifarr[i]<arr[min_idx]:min_idx=iarr[unsorted_idx],arr[min_idx]=arr[min_idx],arr[unsorted_idx]sorted_idx=unsorted_idxunsorted_idx+=1# Drawing barsdelay=100# Change the value to adjust the delay in millisecondswin.fill((0,0,0))foriinrange(arr_len):color=(255,255,255)ifi<=sorted_idxelse(0,255,0)pygame.draw.rect(win,color,(i*(win_width/arr_len),win_height-arr[i],win_width/arr_len,arr[i]))pygame.display.update()pygame.time.wait(delay)# Event handling looprunning=Truewhilerunning:foreventinpygame.event.get():ifevent.type==pygame.QUIT:running=False# Quit PyGamepygame.quit()
Output:
