forked from geekcomputers/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge-sort.py
53 lines (37 loc) · 943 Bytes
/
Merge-sort.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
52
53
#merge sort
l = []
n = int(input("Enter number of elements in the list: "))
for i in range(n):
temp = int(input("Enter element"+str(i+1)+': '))
l += [temp]
def merge_sort(L):
mid = int( (len(L) - 1)/2 )
if len(L) > 2:
a = merge_sort(L[0:mid])
b = merge_sort(L[mid:len(L)])
elif len(L) == 2:
a = [L[0]]
b = [L[1]]
else:
return L
i = 0
j = 0
new = []
while (i!= len(a) or j != len(b)):
if i < len(a) and j < len(b):
if a[i] < b[j]:
new += [a[i]]
i += 1
else:
new +=[b[j]]
j += 1
elif i == len(a) and j != len(b):
new += [b[j]]
j += 1
elif j == len(b) and i != len(a):
new += [a[i]]
i += 1
else:
break
return new
print(merge_sort(l))