Skip to content

Commit 5e08ff9

Browse files
geon0325goswami-rahul
authored andcommitted
Added simulation features in insertion & selection sorts (keon#333)
* Added simulation feature * Added simulation feature * Update insertion_sort.py * Update selection_sort.py * Update insertion_sort.py * Update selection_sort.py * Update bubble_sort.py * Update bubble_sort.py * Update insertion_sort.py * Update selection_sort.py
1 parent 409ae68 commit 5e08ff9

3 files changed

Lines changed: 26 additions & 4 deletions

File tree

algorithms/sort/bubble_sort.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,9 @@ def swap(i, j):
1717
n = len(arr)
1818
swapped = True
1919

20+
iteration = 0
2021
if simulation:
21-
print(arr)
22+
print("iteration",iteration,":",*arr)
2223

2324
while swapped:
2425
swapped = False
@@ -27,6 +28,7 @@ def swap(i, j):
2728
swap(i - 1, i)
2829
swapped = True
2930
if simulation:
30-
print(arr)
31+
iteration = iteration + 1
32+
print("iteration",iteration,":",*arr)
3133

3234
return arr

algorithms/sort/insertion_sort.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,25 @@
1-
def insertion_sort(arr):
1+
def insertion_sort(arr, simulation=False):
22
""" Insertion Sort
33
Complexity: O(n^2)
44
"""
5+
6+
iteration = 0
7+
if simulation:
8+
print("iteration",iteration,":",*arr)
9+
510
for i in range(len(arr)):
611
cursor = arr[i]
712
pos = i
13+
814
while pos > 0 and arr[pos - 1] > cursor:
915
# Swap the number down the list
1016
arr[pos] = arr[pos - 1]
1117
pos = pos - 1
1218
# Break and do the final swap
1319
arr[pos] = cursor
20+
21+
if simulation:
22+
iteration = iteration + 1
23+
print("iteration",iteration,":",*arr)
1424

1525
return arr

algorithms/sort/selection_sort.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,23 @@
1-
def selection_sort(arr):
1+
def selection_sort(arr, simulation=False):
22
""" Selection Sort
33
Complexity: O(n^2)
44
"""
5+
iteration = 0
6+
if simulation:
7+
print("iteration",iteration,":",*arr)
8+
59
for i in range(len(arr)):
610
minimum = i
11+
712
for j in range(i + 1, len(arr)):
813
# "Select" the correct value
914
if arr[j] < arr[minimum]:
1015
minimum = j
1116

1217
arr[minimum], arr[i] = arr[i], arr[minimum]
18+
19+
if simulation:
20+
iteration = iteration + 1
21+
print("iteration",iteration,":",*arr)
22+
1323
return arr

0 commit comments

Comments
 (0)