Last active 1730124210

in python

mergesort.py Raw
1def merge_sort(array):
2 """split and recursively sort an array"""
3
4 if len(array) <= 1:
5 return array
6
7 mid = len(array) // 2
8 left_slice = array[:mid]
9 right_slice = array[mid:]
10
11 return merge(merge_sort(left_slice), merge_sort(right_slice))
12
13
14def merge(left, right):
15 """merge 2 sorted arrays"""
16 sorted_array = []
17 i, j = 0, 0
18
19 while i < len(left) and j < len(right):
20 if left[i] < right[j]:
21 sorted_array.append(left[i])
22 i += 1
23 else:
24 sorted_array.append(right[j])
25 j += 1
26
27 # add remaining items, if any
28 sorted_array.extend(left[i:])
29 sorted_array.extend(right[j:])
30 return sorted_array
31
32
33import random
34
35
36def generate_random_list(size):
37 return random.sample(range(size), size)
38
39
40a = generate_random_list(1000)
41b = merge_sort(a)
42
43print(f"random array : \n{a}")
44print(f"sorted array : \n{b}")