Skip to content

Commit fc47ea2

Browse files
committed
Added Selection Sort and frame to hold buttons
1 parent 6b90e15 commit fc47ea2

3 files changed

Lines changed: 36 additions & 4 deletions

File tree

472 Bytes
Binary file not shown.

algorithms.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,17 @@ def bubble_sort(array):
55
if array[j] > array[j+1]:
66
array[j], array[j+1] = array[j+1], array[j]
77
yield array, j, j+1
8+
9+
def selection_sort(array):
10+
n = len(array)
11+
for i in range(n):
12+
min_idx = i
13+
for j in range(i+1, n):
14+
if array[j] < array[min_idx]:
15+
min_idx = j
16+
# Pause after each comparison so to enable highlighting the bars
17+
yield array, i, j
18+
if min_idx != i:
19+
array[i], array[min_idx] = array[min_idx], array[i]
20+
# Pause after the swap
21+
yield array, i, min_idx

main.py

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from algorithms import bubble_sort
1+
from algorithms import bubble_sort, selection_sort
22
import tkinter as tk
33
import random
44

@@ -24,7 +24,7 @@ def draw_array(array, color_array):
2424
root.update_idletasks()
2525

2626
#Function to Start Sorting using Bubble Sort
27-
def start_sort():
27+
def start_bubble_sort():
2828
color_array = ['blue' for _ in range(len(array))]
2929
for arr, i, j in bubble_sort(array):
3030
color_array[i] = 'red'
@@ -33,12 +33,30 @@ def start_sort():
3333
color_array[i] = 'blue'
3434
color_array[j] = 'blue'
3535

36+
#Function to Start Sorting using Selection Sort
37+
def start_selection_sort():
38+
color_array = ['blue' for _ in range(len(array))]
39+
for arr, i, j in selection_sort(array):
40+
color_array[i] = 'red'
41+
color_array[j] = 'red'
42+
draw_array(arr, color_array)
43+
color_array[i] = 'blue'
44+
color_array[j] = 'blue'
45+
3646
#Random Array
3747
array = [random.randint(10, 100) for _ in range(50)]
3848

49+
#Create a Frame for the Buttons
50+
button_frame = tk.Frame(root)
51+
button_frame.pack(pady=10)
52+
3953
#'Start Bubble Sort' Button
40-
start_button = tk.Button(root, text="Start Bubble Sort", command=start_sort)
41-
start_button.pack(pady=10)
54+
start_bubble_button = tk.Button(button_frame, text="Start Bubble Sort", command=start_bubble_sort)
55+
start_bubble_button.pack(side=tk.LEFT, padx=5)
56+
57+
#'Start Selection Sort' Button
58+
start_selection_button = tk.Button(button_frame, text="Start Selection Sort", command=start_selection_sort)
59+
start_selection_button.pack(side=tk.LEFT, padx=5)
4260

4361
color_array = ['blue' for _ in range(len(array))]
4462
draw_array(array, color_array)

0 commit comments

Comments
 (0)