Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Building and visualizing Sudoku Game Using Pygame
Next article icon

An algorithm likeBinary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. TheGraphical User Interface(GUI) is implemented inPython usingpygame 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.
  • Orange color highlights the left and right bars.

Below is the implementation of the above visualizer:

Python
# Python implementation of the# Sorting visualiser: Insertion Sort# Importsimportpygameimportrandomimporttimepygame.font.init()startTime=time.time()# Total windowscreen=pygame.display.set_mode((900,650))# Title and Iconpygame.display.set_caption("BINARY 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 looprun=True# Window size and some initialswidth=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 SortdefheapSort(array):n=len(array)foriinrange(n//2-1,-1,-1):heapify(array,i,n)foriinrange(n-1,0,-1):array[i],array[0]=array[0],array[i]heapify(array,0,i)defheapify(array,root,size):left=root*2+1right=root*2+2largest=rootifleft<sizeandarray[left]>array[largest]:largest=leftifright<sizeandarray[right]>array[largest]:largest=rightiflargest!=root:array[largest],array[root]=array[root],array[largest]heapify(array,largest,size)# Function to generate new Arraydefgenerate_arr():foriinrange(1,151):arr_clr[i]=clr[0]array[i]=random.randrange(1,100)heapSort(array)# Initially generate a arraygenerate_arr()# Function to refill the# updates on the windowdefrefill():screen.fill((255,255,255))draw()pygame.display.update()pygame.time.delay(200)defbinarySearch(array,key):left=0right=len(array)-1whileleft<right:arr_clr[left]=clr[1]arr_clr[right]=clr[1]refill()refill()mid=left+(right-left)//2ifarray[mid]==key:arr_clr[left]=clr[0]arr_clr[right]=clr[0]arr_clr[mid]=clr[2]return1elifarray[mid]<key:arr_clr[left]=clr[0]left=mid+1else:arr_clr[right]=clr[0]right=mid-1refill()arr_clr[left]=clr[0]arr_clr[right]=clr[0]refill()return-1# Function to Draw the array valuesdefdraw():# Text should be renderedtxt=fnt.render("SEARCH: PRESS 'ENTER'",1,(0,0,0))# Position where text is placedscreen.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)//150boundry_arr=900/150boundry_grp=550/100pygame.draw.line(screen,(0,0,0),(0,95),(900,95),6)# Drawing the array values as linesforiinrange(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 openwhilerun:# backgroundscreen.fill((255,255,255))# Event handler stores all eventforeventinpygame.event.get():# If we click Close button in windowifevent.type==pygame.QUIT:run=Falseifevent.type==pygame.KEYDOWN:ifevent.key==pygame.K_r:key=0foundkey=0generate_arr()ifevent.key==pygame.K_n:foundkey=0key=0foriinrange(0,len(array)):arr_clr[i]=clr[0]ifevent.key==pygame.K_RETURNandkey!=0:foundkey=binarySearch(array,key)ifevent.key==pygame.K_0:key=key*10ifevent.key==pygame.K_1:key=key*10+1ifevent.key==pygame.K_2:key=key*10+2ifevent.key==pygame.K_3:key=key*10+3ifevent.key==pygame.K_4:key=key*10+4ifevent.key==pygame.K_5:key=key*10+5ifevent.key==pygame.K_6:key=key*10+6ifevent.key==pygame.K_7:key=key*10+7ifevent.key==pygame.K_8:key=key*10+8ifevent.key==pygame.K_9:key=key*10+9draw()pygame.display.update()pygame.quit()

Output:


Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp