Madhan-Alagarsamy commited on
Commit
f6d5e24
·
verified ·
1 Parent(s): 69b3ab8

Upload 6.py

Browse files
Files changed (1) hide show
  1. 6.py +42 -0
6.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def merge(S1, S2, S):
2
+ i = j = 0
3
+ while i + j < len(S):
4
+ if j == len(S2) or (i < len(S1) and S1[i] < S2[j]):
5
+ S[i + j] = S1[i]
6
+ i += 1
7
+ else:
8
+ S[i + j] = S2[j]
9
+ j += 1
10
+ def merge_sort(S):
11
+ n = len(S)
12
+ if n < 2:
13
+ return
14
+ mid = n // 2
15
+ S1 = S[0:mid]
16
+ S2 = S[mid:n]
17
+ merge_sort(S1)
18
+ merge_sort(S2)
19
+ merge(S1, S2, S)
20
+
21
+
22
+ # Main Program
23
+ while True:
24
+ S = []
25
+ print("\n\tImplementation of the Recursive Merge-Sort Algorithm")
26
+ print("\t\tfor Python's array-based list class")
27
+ n = int(input("Enter number of elements (greater than zero): "))
28
+ if n >= 1:
29
+ print("Enter the elements one by one:")
30
+ for _ in range(n):
31
+ S.append(int(input()))
32
+ print("\nOutput")
33
+ print("---------")
34
+ print("Elements before sorting:", S)
35
+ merge_sort(S)
36
+ print("Elements after sorting :", S)
37
+ else:
38
+ print("Invalid input!")
39
+ c = int(input("\nTo continue press 1 otherwise press 0: "))
40
+ if c != 1:
41
+ print("Program Terminated")
42
+ break