"Program to perform Merge sort"
# Code for merge sort
def merge(a,b):
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 to split The List
def mergesort(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = int(len(x)/2)
a = mergesort(x[:middle])
b = mergesort(x[middle:])
return merge(a,b)
def main():
List_size=int(input("Enter the Number of Elements : "))
Slist=[]
for i in range(0,List_size):
print ("Enter the ", i ," item ")
E_item=int(input("The Value : "))
Slist.append(E_item)
print ("The Unsortede List")
print (Slist)
print ("The sorted List is")
print (mergesort(Slist))
main()
# Code for merge sort
def merge(a,b):
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 to split The List
def mergesort(x):
if len(x) == 0 or len(x) == 1:
return x
else:
middle = int(len(x)/2)
a = mergesort(x[:middle])
b = mergesort(x[middle:])
return merge(a,b)
def main():
List_size=int(input("Enter the Number of Elements : "))
Slist=[]
for i in range(0,List_size):
print ("Enter the ", i ," item ")
E_item=int(input("The Value : "))
Slist.append(E_item)
print ("The Unsortede List")
print (Slist)
print ("The sorted List is")
print (mergesort(Slist))
main()
No comments:
Post a Comment