File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #merge sort
2+
3+ l = []
4+
5+ n = int (input ("Enter number of elements in the list: " ))
6+
7+ for i in range (n ):
8+ temp = int (input ("Enter element" + str (i + 1 )+ ': ' ))
9+ l += [temp ]
10+
11+ def merge_sort (L ):
12+
13+ mid = int ( (len (L ) - 1 )/ 2 )
14+
15+ if len (L ) > 2 :
16+ a = merge_sort (L [0 :mid ])
17+ b = merge_sort (L [mid :len (L )])
18+
19+ elif len (L ) == 2 :
20+ a = [L [0 ]]
21+ b = [L [1 ]]
22+ else :
23+ return L
24+
25+ i = 0
26+ j = 0
27+ new = []
28+ while (i != len (a ) or j != len (b )):
29+
30+ if i < len (a ) and j < len (b ):
31+
32+ if a [i ] < b [j ]:
33+ new += [a [i ]]
34+ i += 1
35+
36+ else :
37+ new += [b [j ]]
38+ j += 1
39+
40+ elif i == len (a ) and j != len (b ):
41+ new += [b [j ]]
42+ j += 1
43+
44+ elif j == len (b ) and i != len (a ):
45+ new += [a [i ]]
46+ i += 1
47+
48+ else :
49+ break
50+
51+ return new
52+
53+ print (merge_sort (l ))
You can’t perform that action at this time.
0 commit comments