Skip to content

Commit 751e9b8

Browse files
author
Benjamin Fein
committed
Fixes variable names and adds documentation
1 parent 94a9323 commit 751e9b8

File tree

1 file changed

+38
-23
lines changed

1 file changed

+38
-23
lines changed

sorts/recursive_mergesort_array.py

Lines changed: 38 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
"""A merge sort which accepts an array as input and recursively splits an array in half and sorts and combines them. """
2+
3+
"""https://en.wikipedia.org/wiki/Merge_sort """
4+
5+
16
def merge(arr: list[int]) -> list[int]:
27
"""Return a sorted array.
38
>>> merge([10,9,8,7,6,5,4,3,2,1])
@@ -8,32 +13,42 @@ def merge(arr: list[int]) -> list[int]:
813
[1, 2, 3, 9, 10, 15, 22, 23]
914
"""
1015
if len(arr) > 1:
11-
middle_length = len(arr) // 2
12-
left_array = arr[:middle_length]
13-
right_array = arr[middle_length:]
16+
middle_length = len(arr) // 2 ##Finds the middle of the array
17+
left_array = arr[
18+
:middle_length
19+
] ##Creates an array of the elements in the first half.
20+
right_array = arr[
21+
middle_length:
22+
] ##Creates an array of the elements in the second half.
1423
left_size = len(left_array)
1524
right_size = len(right_array)
16-
merge(left_array)
17-
merge(right_array)
18-
i = 0
19-
j = 0
20-
k = 0
21-
while i < left_size and j < right_size:
22-
if left_array[i] < right_array[j]:
23-
arr[k] = left_array[i]
24-
i = i + 1
25+
merge(left_array) ## Starts sorting the left.
26+
merge(right_array) ##Starts sorting the right
27+
leftIndex = 0 ##Left Counter
28+
rightIndex = 0 ## Right Counter
29+
index = 0 ## Position Counter
30+
while (
31+
leftIndex < left_size and rightIndex < right_size
32+
): ##Runs until the lowers size of the left and right are sorted.
33+
if left_array[leftIndex] < right_array[rightIndex]:
34+
arr[index] = left_array[leftIndex]
35+
leftIndex = leftIndex + 1
2536
else:
26-
arr[k] = right_array[j]
27-
j = j + 1
28-
k = k + 1
29-
while i < left_size:
30-
arr[k] = left_array[i]
31-
i = i + 1
32-
k = k + 1
33-
while j < right_size:
34-
arr[k] = right_array[j]
35-
j = j + 1
36-
k = k + 1
37+
arr[index] = right_array[rightIndex]
38+
rightIndex = rightIndex + 1
39+
index = index + 1
40+
while (
41+
leftIndex < left_size
42+
): ##Adds the left over elements in the left half of the array
43+
arr[index] = left_array[leftIndex]
44+
leftIndex = leftIndex + 1
45+
index = index + 1
46+
while (
47+
rightIndex < right_size
48+
): ##Adds the left over elements in the right half of the array
49+
arr[index] = right_array[rightIndex]
50+
rightIndex = rightIndex + 1
51+
index = index + 1
3752
return arr
3853

3954

0 commit comments

Comments
 (0)