Return a sorted array. >>> merge([10,9,8,7,6,5,4,3,2,1]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([1,2,3,4,5,6,7,8,9,10]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> merge([10,22,1,2,3,9,15,23]) [1, 2, 3, 9, 10, 15, 22, 23] >>> merge([100]) [100] >>> merge([]) []
(arr: list[int])
| 6 | |
| 7 | |
| 8 | def merge(arr: list[int]) -> list[int]: |
| 9 | """Return a sorted array. |
| 10 | >>> merge([10,9,8,7,6,5,4,3,2,1]) |
| 11 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 12 | >>> merge([1,2,3,4,5,6,7,8,9,10]) |
| 13 | [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
| 14 | >>> merge([10,22,1,2,3,9,15,23]) |
| 15 | [1, 2, 3, 9, 10, 15, 22, 23] |
| 16 | >>> merge([100]) |
| 17 | [100] |
| 18 | >>> merge([]) |
| 19 | [] |
| 20 | """ |
| 21 | if len(arr) > 1: |
| 22 | middle_length = len(arr) // 2 # Finds the middle of the array |
| 23 | left_array = arr[ |
| 24 | :middle_length |
| 25 | ] # Creates an array of the elements in the first half. |
| 26 | right_array = arr[ |
| 27 | middle_length: |
| 28 | ] # Creates an array of the elements in the second half. |
| 29 | left_size = len(left_array) |
| 30 | right_size = len(right_array) |
| 31 | merge(left_array) # Starts sorting the left. |
| 32 | merge(right_array) # Starts sorting the right |
| 33 | left_index = 0 # Left Counter |
| 34 | right_index = 0 # Right Counter |
| 35 | index = 0 # Position Counter |
| 36 | while ( |
| 37 | left_index < left_size and right_index < right_size |
| 38 | ): # Runs until the lowers size of the left and right are sorted. |
| 39 | if left_array[left_index] < right_array[right_index]: |
| 40 | arr[index] = left_array[left_index] |
| 41 | left_index += 1 |
| 42 | else: |
| 43 | arr[index] = right_array[right_index] |
| 44 | right_index += 1 |
| 45 | index += 1 |
| 46 | while ( |
| 47 | left_index < left_size |
| 48 | ): # Adds the left over elements in the left half of the array |
| 49 | arr[index] = left_array[left_index] |
| 50 | left_index += 1 |
| 51 | index += 1 |
| 52 | while ( |
| 53 | right_index < right_size |
| 54 | ): # Adds the left over elements in the right half of the array |
| 55 | arr[index] = right_array[right_index] |
| 56 | right_index += 1 |
| 57 | index += 1 |
| 58 | return arr |
| 59 | |
| 60 | |
| 61 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected