File size: 1,183 Bytes
f6d5e24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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