forked from OmkarPathak/pygorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge_sort.py
More file actions
47 lines (40 loc) · 1.04 KB
/
merge_sort.py
File metadata and controls
47 lines (40 loc) · 1.04 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
# Author: OMKAR PATHAK
# Created On: 31st July 2017
# Best = Average = Worst = O(nlog(n))
# merge function to merge the separated lists
def merge(a,b):
""" Function to merge two arrays """
c = []
while len(a) != 0 and len(b) != 0:
if a[0] < b[0]:
c.append(a[0])
a.remove(a[0])
else:
c.append(b[0])
b.remove(b[0])
if len(a) == 0:
c += b
else:
c += a
return c
# Code for merge sort
def sort(x):
""" Function to sort an array using merge sort algorithm """
if len(x) == 0 or len(x) == 1:
return x
else:
middle = len(x)//2
a = sort(x[:middle])
b = sort(x[middle:])
return merge(a,b)
# time complexities
def bestcase_complexity():
return 'O(nlogn)'
def averagecase_complexity():
return 'O(nlogn)'
def worstcase_complexity():
return 'O(nlogn)'
# easily retrieve the source code of the sort function
def get_code():
import inspect
return inspect.getsource(sort), inspect.getsource(merge)