-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_merge_sort.py
More file actions
78 lines (57 loc) · 1.72 KB
/
Copy path06_merge_sort.py
File metadata and controls
78 lines (57 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# Merge Sort
# A merge sort algorithm splits an array into halves, sorts each
# half and merges the sorted halves back together
#################################################################
# FUNCTION TO MERGE SORT
def merge_sort(array):
if len(array) > 1:
mid = len(array) // 2
left = array[:mid]
right = array[mid:]
# Recursively sort both halves
merge_sort(left)
merge_sort(right)
i = j = k = 0
# Merge sorted halves
while i < len(left) and j < len(right):
if left[i] < right[j]:
array[k] = left[i]
i += 1
else:
array[k] = right[j]
j += 1
k += 1
# Copy remaining elements
while i < len(left):
array[k] = left[i]
i += 1
k += 1
while j < len(right):
array[k] = right[j]
j += 1
k += 1
# SET VARIABLES
# the array to be sorted
array = [38, 27, 43, 3, 9, 82, 10]
# CALL THE FUNCTION
merge_sort(array)
# PRINT RESULTS
print("Sorted array is:", array)
#################################################################
# O NOTATION - Log-Linear Time O(n log n)
# Log-Linear Time o notation represents an algorithm that splits
# the input and processes each element
# # UNCOMMENT HERE DOWN
# # Initialize the iterations sum variable
# iterations = 0
# # Get the length of the array
# n = len(array)
# log_n = 0
# # Calculate long n (how many times we can halve n before reaching 1)
# while n > 1:
# n = n // 2
# log_n += 1
# # Multiple log n by n to get O(n log n)
# iterations = n * log_n
# # PRINT RESULTS
# print("The total iterations are: ", iterations)