Raptor472/Python-App-for-Sorting-Algorithm-visual-simulation
0
1import gradio as gr2import random3 4def insertion_sort_colored(arr):5 steps = []6 explanation = "The first number is always concidered as 'sorted', as there are no numbers before it to compare with"7 steps.append(color_step(arr, 0, None, explanation)) # initial state, all red except first8 9 10 for i in range(1, len(arr)):11 key = arr[i]12 j = i - 113 last_changed = None # track only if position changes14 compared = []15 change_times = 016 17 while j >= 0 and arr[j] > key:18 arr[j + 1] = arr[j]19 last_changed = j + 1 # updated position of the shifted element20 j -= 121 last_changed = j + 122 # Insert key in its position23 arr[j + 1] = key24 25 # If key moved from its original position i, highlight it26 if j + 1 != i:27 28 for k in range(0,i-j-1):29 compared.append(f"<span style='color:orange; font-weight:bold'>{arr[j+1]}</span> < {arr[i-k]}")30 31 if j >= 0 and j != j+1:32 compared.append(f"<span style='color:orange; font-weight:bold'>{arr[j+1]}</span> > {arr[j]}")33 elif j >= 0 and j == j+1:34 compared.append(f"<span style='color:orange; font-weight:bold'>{arr[j+1]}</span> = {arr[j]}")35 36 explanation = f"{' | '.join(compared)} <br> Old index {i} → New index {j+1}."37 38 else:39 explanation = f"{key} stayed in place."40 41 steps.append(color_step(arr, i, last_changed, explanation))42 return "<br><br>".join(steps)43 44def color_step(arr, sorted_index, last_changed, message=""):45 result = []46 for idx, num in enumerate(arr):47 if idx == last_changed:48 color = "orange"49 weight = "bold"50 elif idx <= sorted_index:51 color = "green"52 weight = "bold"53 else:54 color = "red"55 weight = "normal"56 57 if num.is_integer() == True:58 num = int(num)59 result.append(f"<span style='color:{color}; font-weight:{weight}'>{num}</span>")60 return " ".join(result) + f"<br><small>{message}</small>"61 62def nums(user_input):63 if user_input != "":64 numbers = []65 66 try:67 for n in user_input.split(","):68 if len(numbers) >= 20:69 break70 numbers.append(float(n.strip()))71 72 except (TypeError, ValueError):73 return ("⚠️Input Contains Invalid Character!")74 75 76 return insertion_sort_colored(numbers)77 78 79 80def generate_list(amount,min,max):81 82 try:83 arr = random.sample(range(int(min), int(max)), int(amount))84 text = ", ".join(str(x) for x in arr)85 return text,None86 except (TypeError, ValueError):87 return "","⚠️Minimum random number is greater than maximum!"88 89 90#Logic for the "Clear" button, which will blank both the input and output boxes91def clear():92 output = ""93 input = ""94 return output,input95 96 97with gr.Blocks() as demo:98 99 input = gr.Textbox(label="Input List (MAX 20 numbers)", placeholder = "1, 2, 3, 4, 5...", max_lines = 1)100 output = gr.HTML(label="Sorting Steps with Colors")101 102 with gr.Row():103 run_btn = gr.Button("Sort")104 random_btn = gr.Button("Randomize") #, icon = "a"105 clear_btn = gr.Button("Clear")106 107 with gr.Row():108 random_amount = gr.Number(label="Amount Of Random Numbers (1-20)", value=10, precision=0, interactive = True, maximum = 20, minimum = 1)109 random_min = gr.Number(label="Minimum Value Of Random Numbers", value=1, precision=0, interactive = True, maximum = 9998, minimum = -9999)110 random_max = gr.Number(label="Maximum Value Of Random Numbers", value=100, precision=0, interactive = True, maximum = 9999, minimum = -9998)111 112 run_btn.click(fn=nums, inputs=input, outputs=output)113 random_btn.click(fn=generate_list, inputs=[random_amount,random_min,random_max],outputs=[input,output])114 clear_btn.click(fn=clear, inputs=None, outputs=[output,input])115 116demo.launch()