CoolFace
Apppublic

andy2200159/bubble_sort_simulation

sourceHugging Facemitupdated 10mo agoView on Hugging Face
0likes
app.py59 linesDownload Raw Back to root
1import gradio as gr2 3def bubble_sort_simulation(user_input):4    """5    This function takes a string of numbers, sorts them using Bubble Sort,6    and returns a log of the steps for visualization.7    """8    # Error Handling: Try to convert input to a list of integers9    try:10        # Split the string by commas and convert to integers11        nums = [int(x.strip()) for x in user_input.split(',')]12    except ValueError:13        return "Error: Please enter valid numbers separated by commas (e.g., 5, 1, 4, 2)."14 15    steps_log = [] # This will store the history of changes to show the user16    steps_log.append(f"Initial List: {nums}\n")17    18    n = len(nums)19    20    # --- Algorithm Implementation: Bubble Sort ---21    # Loop through the list n times22    for i in range(n):23        swapped = False24        steps_log.append(f"--- Pass {i+1} ---")25        26        # Inner loop to compare side-by-side elements27        for j in range(0, n - i - 1):28            # COMPARE: Check if the left number is bigger than the right number29            if nums[j] > nums[j+1]:30                # SWAP: If yes, swap them31                nums[j], nums[j+1] = nums[j+1], nums[j]32                swapped = True33                steps_log.append(f"Swapped {nums[j+1]} and {nums[j]}: Current State -> {nums}")34            else:35                steps_log.append(f"No swap needed for {nums[j]} and {nums[j+1]}")36 37        # If no swaps occurred in this pass, the list is already sorted (Optimization)38        if not swapped:39            steps_log.append("No swaps made this pass. List is sorted!")40            break41            42    return "\n".join(steps_log)43 44# --- UI Setup using Gradio  ---45# Want a simple interface with one input box and one output box46with gr.Blocks() as demo:47    gr.Markdown("# Bubble Sort Visualizer")48    gr.Markdown("Enter numbers separated by commas to see how Bubble Sort swaps them in order.")49    50    with gr.Row():51        input_box = gr.Textbox(label="Input List (e.g., 5, 3, 8, 1)")52        output_box = gr.Textbox(label="Sorting Steps Log", lines=10)53    54    # Button to trigger the function55    sort_btn = gr.Button("Sort My List")56    sort_btn.click(fn=bubble_sort_simulation, inputs=input_box, outputs=output_box)57 58# Launch the app59demo.launch()