shukdevdatta123's picture
Update app.py
4d1e704 verified
raw
history blame
3.48 kB
import streamlit as st
import time
import random
import numpy as np
# Bubble Sort Algorithm with animation
def bubble_sort(arr):
steps = []
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
steps.append(list(arr)) # Record the state of the array after each step
return steps
# Insertion Sort Algorithm with animation
def insertion_sort(arr):
steps = []
for i in range(1, len(arr)):
key = arr[i]
j = i - 1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
steps.append(list(arr)) # Record the state of the array after each step
arr[j + 1] = key
steps.append(list(arr)) # Record the state after inserting the key
return steps
# Selection Sort Algorithm with animation
def selection_sort(arr):
steps = []
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
steps.append(list(arr)) # Record the state after each swap
return steps
# Quick Sort Algorithm with animation
def quick_sort(arr):
steps = []
def quick_sort_helper(arr, steps):
if len(arr) <= 1:
return arr, steps
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
steps.append(list(arr)) # Record the state before sorting the partitions
left_sorted, steps = quick_sort_helper(left, steps)
right_sorted, steps = quick_sort_helper(right, steps)
return left_sorted + middle + right_sorted, steps
sorted_arr, steps = quick_sort_helper(arr, steps)
return steps
# Function to handle animation in the streamlit app
def animate_sorting(steps):
for step in steps:
st.write(step)
time.sleep(0.5) # Adjust sleep time to control animation speed
# Streamlit App Interface
def main():
st.title("Sorting Algorithms Visualization")
# Input array from user
user_input = st.text_input("Enter a list of numbers (comma separated):", "64, 34, 25, 12, 22, 11, 90")
# Convert the input into a list of integers
if user_input:
try:
arr = [int(x) for x in user_input.split(',')]
except ValueError:
st.error("Please enter a valid list of integers.")
return
# Select the sorting algorithm
algorithm = st.selectbox("Select sorting algorithm:", ("Bubble Sort", "Insertion Sort", "Selection Sort", "Quick Sort"))
# Start the animation on button press
if st.button('Sort'):
steps = []
if algorithm == "Bubble Sort":
steps = bubble_sort(arr)
elif algorithm == "Insertion Sort":
steps = insertion_sort(arr)
elif algorithm == "Selection Sort":
steps = selection_sort(arr)
elif algorithm == "Quick Sort":
steps = quick_sort(arr)
# Animate the sorting process
animate_sorting(steps)
# Display the final sorted array
st.write("Sorted Array:", arr)
# Run the app
if __name__ == "__main__":
main()