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
+
1
6
def merge (arr : list [int ]) -> list [int ]:
2
7
"""Return a sorted array.
3
8
>>> merge([10,9,8,7,6,5,4,3,2,1])
@@ -8,32 +13,42 @@ def merge(arr: list[int]) -> list[int]:
8
13
[1, 2, 3, 9, 10, 15, 22, 23]
9
14
"""
10
15
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.
14
23
left_size = len (left_array )
15
24
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
25
36
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
37
52
return arr
38
53
39
54
0 commit comments