Saad121s/Insertion-Sort
0
1import gradio as gr 2import matplotlib.pyplot as plt #To draw the chart 3import time #To slow down the code for the user to see4 5def insertion_sort(text_input):6 #Try/Catch statement to avoid an error, when user enters invalid list7 try:8 if not text_input:9 return None10 array = [int(x) for x in text_input.split(',')] #Convert string input to a list of integars11 except ValueError:12 return None 13 14 #To draw the chart15 def draw_chart(data, highlight_index=None):16 fig, ax = plt.subplots(figsize=(6, 4)) #Size of frame of output17 18 #Make the background black19 fig.patch.set_facecolor('black')20 ax.set_facecolor('black')21 22 #Make the bars cyan23 colors = ['#00E5FF'] * len(data) 24 #Paint the current moving bar red.25 if highlight_index is not None:26 colors[highlight_index] = '#FF204E' 27 28 29 # Find the minimum value. If it's negative, shift everything up.30 # We add +2 extra so the smallest bar isn't invisible.31 min_val = min(data)32 if min_val < 0:33 visual_heights = [x + abs(min_val) + 2 for x in data]34 else:35 visual_heights = data # If all positive, just use normal heights36 37 # Draw the bars38 bars = ax.bar(range(len(data)), visual_heights, color=colors, width=0.8)39 40 # Add Numbers to the bars41 for bar, real_value in zip(bars, data):42 ax.text(43 bar.get_x() + bar.get_width() / 2, 44 0.5, # Position at bottom45 str(real_value), # Turn the number into a str so we can print it46 ha='center', # Center the text horizontally47 va='bottom', # Center the text vertically 48 color='black', 49 fontweight='bold',50 fontsize=1251 )52 53 ax.axis('off') #Remove the grid54 return fig55 56 #Logic of the app57 for i in range(1, len(array)):58 value = array[i] 59 j = i - 1 60 61 while j >= 0 and value < array[j]: 62 array[j+1] = array[j]63 array[j] = value 64 65 # Show the red bar moving66 yield draw_chart(array, highlight_index=j)67 #Slow down so the user can the output68 time.sleep(0.9) 69 70 j -= 171 72 array[j+1] = value73 74 yield draw_chart(array) #repaint75 76 #The starting UI77with gr.Blocks() as demo:78 gr.Markdown("# Insertion Sort")79 80 inp = gr.Textbox(label="Enter Numbers")81 out = gr.Plot(label="Animation")82 btn = gr.Button("Sort", variant="primary")83 btn.click(fn=insertion_sort, inputs=inp, outputs=out)84 85demo.launch()