Ternary Search Visualization using Pygame in Python

An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library.
Approach
Generate random array, sort it using any sorting algorithm, and fill the pygame window with bars. Bars are straight vertical lines, which represent array elements.
- Set all bars to green color.
- Use pygame.time.delay() to slow down the algorithm, so that we can see the searching process.
- Implement a timer to see how the algorithm performs.
- The actions are performed using ‘pygame.event.get()’ method, which stores all the events which the user performs, such as start, reset.
- The blue color is used to highlight the bar equal to the key if found.
- Red color highlights the left and right bars.
- Orange color highlights the mid1 and mid2 bars.
Below is the implementation of the above visualizer.
Python
| # Python implementation of the # Sorting visualiser: Insertion Sort  Âimportpygame importrandom importtime  Â Âpygame.font.init() startTime =time.time()  Â# Total window screen =pygame.display.set_mode(     (900, 650) )  Â# Title and Icon pygame.display.set_caption(     "TERNARY SEARCH VISUALISER")  Â# Uncomment below lines for setting # up the icon for the visuliser # img = pygame.image.load('sorticon.png') # pygame.display.set_icon(img)  Â# Boolean variable to run # the program in while loop run =True Â# Window size and some initials width =900length =600array =[0]*151key =0foundkey =Falsearr_clr =[(0, 204, 102)]*151clr_ind =0clr =[(0, 204, 102), (255, 0, 0),        (0, 0, 153), (255, 102, 0)] bigfont =pygame.font.SysFont("comicsans", 70) fnt =pygame.font.SysFont("comicsans", 30) fnt1 =pygame.font.SysFont("comicsans", 20)  Â# Sorting Algorithm: Heap Sort defheapSort(array):    Â    n =len(array)      Â    fori inrange(n//2-1, -1, -1):         heapify(array, i, n)      Â    fori inrange(n-1, 0, -1):         array[i], array[0] =array[0], array[i]         heapify(array, 0, i)  Â Âdefheapify(array, root, size):      Â    left =root*2+1    right =root*2+2    largest =root      Â    ifleft < size andarray[left] > array[largest]:         largest =left      Â    ifright < size andarray[right] > array[largest]:         largest =right      Â    iflargest !=root:         array[largest], array[root] =array[root], array[largest]         heapify(array, largest, size)  Â# Function to generate new Array defgenerate_arr():      Â    fori inrange(1, 151):         arr_clr[i] =clr[0]         array[i] =random.randrange(1, 100)     heapSort(array)  Â Â# Initially generate a array generate_arr()  Â# Function to refill the # updates on the window defrefill():      Â    screen.fill((255, 255, 255))     draw()     pygame.display.update()     pygame.time.delay(200)  Â ÂdefternarySearch(array, key):     left =1    right =len(array)-1 Â    whileleft <=right:         pygame.event.pump()         arr_clr[left] =clr[1]         arr_clr[right] =clr[1]         mid1 =left+(right-left)//3        mid2 =right-(right-left)//3        arr_clr[mid1] =clr[3]         arr_clr[mid2] =clr[3]         refill()         pygame.event.pump()         refill()         refill()         arr_clr[left] =clr[0]         arr_clr[right] =clr[0]         arr_clr[mid1] =clr[0]         arr_clr[mid2] =clr[0]          Â        ifkey ==array[mid1]:             arr_clr[mid1] =clr[2]             return1         Â        ifkey ==array[mid2]:             arr_clr[mid1] =clr[2]             return1 Â        ifkey < array[mid1]:             right =mid1-1        elifkey > array[mid2]:             left =mid2+1        else:             left =mid1+1            right =mid2-1        refill()  Â    return-1   Â# Function to Draw the array values defdraw():    Â    # Text should be rendered     txt =fnt.render("SEARCH: PRESS 'ENTER'",                      1, (0, 0, 0))      Â    # Position where text is placed     screen.blit(txt, (20, 20))     txt1 =fnt.render("NEW ARRAY: PRESS 'R'",                       1, (0, 0, 0))     screen.blit(txt1, (20, 40))  Â    txt2 =fnt1.render("ENTER NUMBER TO SEARCH:"+                       str(key), 1, (0, 0, 0))     screen.blit(txt2, (600, 60))  Â    text3 =fnt1.render("Running Time(sec): "+                        str(int(time.time() -startTime)),                         1, (0, 0, 0))     screen.blit(text3, (600, 20))  Â    element_width =(width-150)//150    boundry_arr =900/150    boundry_grp =550/100    pygame.draw.line(screen, (0, 0, 0), (0, 95),                      (900, 95), 6)  Â    # Drawing the array values as lines     fori inrange(1, 151):         pygame.draw.line(screen, arr_clr[i],                          (boundry_arr *i-3, 100),                          (boundry_arr *i-3,                           array[i]*boundry_grp +100), element_width)     iffoundkey ==1:         text4 =bigfont.render("Key Found. Press N to Reset Key", 1, (0, 0, 0))         screen.blit(text4, (100, 300))  Â    eliffoundkey ==-1:         text4 =bigfont.render(             "Key Not Found. Press N to Reset Key", 1, (0, 0, 0))         screen.blit(text4, (30, 300))  Â Â# Program should be run # continuously to keep the window open whilerun:    Â    # background     screen.fill((255, 255, 255))  Â    # Event handler stores all event     forevent inpygame.event.get():  Â        # If we click Close button in window         ifevent.type==pygame.QUIT:             run =False        ifevent.type==pygame.KEYDOWN:              Â            ifevent.key ==pygame.K_r:                 key =0                foundkey =0                generate_arr()              Â            ifevent.key ==pygame.K_n:                 foundkey =0                key =0                fori inrange(0, len(array)):                     arr_clr[i] =clr[0]  Â            ifevent.key ==pygame.K_RETURN andkey !=0:                 foundkey =ternarySearch(array, key)                 print("hello")  Â            ifevent.key ==pygame.K_0:                 key =key*10 Â            ifevent.key ==pygame.K_1:                 key =key*10+1 Â            ifevent.key ==pygame.K_2:                 key =key*10+2 Â            ifevent.key ==pygame.K_3:                 key =key*10+3 Â            ifevent.key ==pygame.K_4:                 key =key*10+4 Â            ifevent.key ==pygame.K_5:                 key =key*10+5 Â            ifevent.key ==pygame.K_6:                 key =key*10+6 Â            ifevent.key ==pygame.K_7:                 key =key*10+7 Â            ifevent.key ==pygame.K_8:                 key =key*10+8 Â            ifevent.key ==pygame.K_9:                 key =key*10+9 Â    draw()     pygame.display.update()  Âpygame.quit()  | 
Output:
 
				 
					


