dooperboop/Bubble-Sort-Simulation
0
1import gradio as gr2 3# This list will store the steps for the Gradio output4def bubble_sort_algorithm(data_list):5 steps = []6 arr = data_list[:] # Work on a copy7 8 n = len(arr)9 10 # Bubble Sort logic with step logging + EARLY EXIT11 for i in range(n):12 swapped = False13 steps.append(f"--- PASS {i+1} START ---")14 15 for j in range(n - i - 1):16 steps.append(f"COMPARE: Checking {arr[j]} and {arr[j+1]}")17 18 if arr[j] > arr[j+1]:19 arr[j], arr[j+1] = arr[j+1], arr[j]20 swapped = True21 steps.append(f"SWAP: {arr[j+1]} ↔ {arr[j]} → {arr}")22 else:23 steps.append("NO SWAP")24 25 steps.append(f"PASS COMPLETE: Array now {arr}")26 27 # EARLY EXIT: If no swaps happened, the list is already sorted28 if not swapped:29 steps.append("EARLY EXIT: No swaps this pass → List is sorted.")30 break31 else:32 steps.append("EARLY EXIT: Atleast one swap this pass → List is not fully sorted.")33 34 35 return arr, steps36 37 38def run_bubble_sort_app(input_string):39 try:40 # Convert input into a list of integers41 data_list = [int(x.strip()) for x in input_string.split(",")]42 except ValueError:43 return "Error: Enter numbers separated by commas.", ""44 45 # Run the Bubble Sort algorithm46 final_sorted_list, step_log = bubble_sort_algorithm(data_list)47 48 # Format the steps for output49 step_output = "\n\n".join(step_log)50 51 return f"{final_sorted_list}", step_output52 53 54# Define the Gradio Interface55with gr.Blocks() as demo:56 gr.Markdown("# Bubble Sort Visualizer (With Early Exit)")57 gr.Markdown("Enter numbers separated by commas (e.g., 8, 3, 1, 5).")58 59 input_box = gr.Textbox(label="Input List", placeholder="e.g., 5, 2, 8, 1")60 sort_button = gr.Button("Run Bubble Sort")61 62 output_result = gr.Textbox(label="Final Sorted List", lines=1)63 output_steps = gr.Textbox(label="Step-by-Step Log", lines=20)64 65 sort_button.click(66 fn=run_bubble_sort_app,67 inputs=[input_box],68 outputs=[output_result, output_steps]69 )70 71demo.launch(theme=gr.themes.Ocean())72 