Spaces:
Configuration error
Configuration error
Commit
·
bd2c426
1
Parent(s):
30e4290
update insertion_sort
Browse files- algorithms.py +14 -11
algorithms.py
CHANGED
|
@@ -3,17 +3,20 @@
|
|
| 3 |
|
| 4 |
def insertion_sort(arr):
|
| 5 |
steps = [] # keep all steps here
|
|
|
|
| 6 |
|
| 7 |
-
for
|
| 8 |
-
key =
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
while i >= 0 and arr[i] > key:
|
| 12 |
-
arr[i + 1] = arr[i]
|
| 13 |
-
i -= 1
|
| 14 |
-
steps.append(arr.copy())
|
| 15 |
-
|
| 16 |
-
arr[i + 1] = key
|
| 17 |
-
steps.append(arr.copy()) # save every moment
|
| 18 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
return steps
|
|
|
|
| 3 |
|
| 4 |
def insertion_sort(arr):
|
| 5 |
steps = [] # keep all steps here
|
| 6 |
+
a = arr.copy()
|
| 7 |
|
| 8 |
+
for i in range(1, len(a)):
|
| 9 |
+
key = a[i]
|
| 10 |
+
j = i - 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
+
while j >= 0 and a[j] > key:
|
| 13 |
+
a[j + 1] = a[j]
|
| 14 |
+
steps.append(
|
| 15 |
+
{"array": a.copy(), "active_index": j + 1, "sorted_boundary": i}
|
| 16 |
+
)
|
| 17 |
+
j -= 1
|
| 18 |
+
a[j + 1] = key
|
| 19 |
+
steps.append(
|
| 20 |
+
{"array": a.copy(), "active_index": j + 1, "sorted_boundary": i}
|
| 21 |
+
) # save every moment
|
| 22 |
return steps
|