Python / 6.py
Madhan-Alagarsamy's picture
Upload 6.py
f6d5e24 verified
def merge(S1, S2, S):
i = j = 0
while i + j < len(S):
if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
S[i + j] = S1[i]
i += 1
else:
S[i + j] = S2[j]
j += 1
def merge_sort(S):
n = len(S)
if n < 2:
return
mid = n // 2
S1 = S[0:mid]
S2 = S[mid:n]
merge_sort(S1)
merge_sort(S2)
merge(S1, S2, S)
# Main Program
while True:
S = []
print("\n\tImplementation of the Recursive Merge-Sort Algorithm")
print("\t\tfor Python's array-based list class")
n = int(input("Enter number of elements (greater than zero): "))
if n >= 1:
print("Enter the elements one by one:")
for _ in range(n):
S.append(int(input()))
print("\nOutput")
print("---------")
print("Elements before sorting:", S)
merge_sort(S)
print("Elements after sorting :", S)
else:
print("Invalid input!")
c = int(input("\nTo continue press 1 otherwise press 0: "))
if c != 1:
print("Program Terminated")
break