-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmerge.py
51 lines (40 loc) · 1.18 KB
/
merge.py
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
""" Implementation of Merge Sort algorithm
"""
def merge(data):
""" MergeSort is a Divide and Conquer algorithm. It divides input array
in two halves, calls itself for the two halves and then merges the
two sorted halves.
:param array: list of elements that needs to be sorted
:type array: list
"""
if len(data) > 1:
mid = len(data) // 2
lefthalf = data[:mid]
righthalf = data[mid:]
merge(lefthalf)
merge(righthalf)
i = j = k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
data[k] = lefthalf[i]
i = i + 1
else:
data[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
data[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
data[k] = righthalf[j]
j = j + 1
k = k + 1
def main():
""" operational function """
arr = [34, 56, 23, 67, 3, 68]
print(f"unsorted array: {arr}")
merge(arr)
print(f" sorted array: {arr}")
if __name__ == "__main__":
main()