JustinY07/MergeSortMakerCISC121
0
1import gradio as gr2 3# This list will store the steps for the Gradio output4def merge_sort_algorithm(data_list):5 steps = []6 7 # Inner recursive function (standard Merge Sort logic)8 def merge_sort(arr):9 if len(arr) > 1:10 mid = len(arr) // 211 left_half = arr[:mid]12 right_half = arr[mid:]13 14 # Log the Division step15 steps.append(f"DIVIDE: Split {arr} → Left: {left_half}, Right: {right_half}")16 17 merge_sort(left_half) # Recurse on left18 merge_sort(right_half) # Recurse on right19 20 # Merge logic (compare elements from left_half and right_half)21 i = j = k = 022 while i < len(left_half) and j < len(right_half):23 if left_half[i] < right_half[j]:24 arr[k] = left_half[i]25 i += 126 else:27 arr[k] = right_half[j]28 j += 129 k += 130 31 # Copy remaining elements32 while i < len(left_half):33 arr[k] = left_half[i]34 i += 135 k += 136 37 while j < len(right_half):38 arr[k] = right_half[j]39 j += 140 k += 141 42 # Log the Merge step43 steps.append(f"MERGE: Combined into {arr}")44 45 return arr46 47 # Start the sort48 sorted_list = data_list[:] # Work on a copy49 merge_sort(sorted_list)50 51 # Return both the result and the step log52 return sorted_list, steps53 54 55def run_merge_sort_app(input_string):56 try:57 # Convert the comma-separated string into a list of integers58 data_list = [int(x.strip()) for x in input_string.split(",")]59 except ValueError:60 return "Error: Enter numbers separated by commas.", ""61 62 # Run the core algorithm63 final_sorted_list, step_log = merge_sort_algorithm(data_list)64 65 # Format the steps for output66 step_output = "\n\n".join(step_log)67 68 return f"{final_sorted_list}", step_output69 70# Define the Gradio Interface71with gr.Blocks() as demo:72 gr.Markdown("# Merge Sort Visualizer")73 gr.Markdown("Enter numbers separated by commas (e.g., 8, 3, 1, 5).")74 75 input_box = gr.Textbox(label="Input List", placeholder="e.g., 5, 2, 8, 1")76 sort_button = gr.Button("Run Merge Sort")77 78 output_result = gr.Textbox(label="Final Sorted List", lines=1)79 output_steps = gr.Textbox(label="Step-by-Step Log", lines=20)80 81 sort_button.click(82 fn=run_merge_sort_app,83 inputs=[input_box],84 outputs=[output_result, output_steps]85 )86 87demo.launch(theme=gr.themes.Citrus())88 