-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathin-place-merge-sort.py
70 lines (49 loc) · 1.46 KB
/
in-place-merge-sort.py
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def merge(arr, start, mid, end):
start2 = mid + 1
# If the direct merge is already sorted
if arr[mid] <= arr[start2]:
return
# Two pointers to maintain start
# of both arrays to merge
while start <= mid and start2 <= end:
# If element 1 is in right place
if arr[start] <= arr[start2]:
start += 1
else:
value = arr[start2]
index = start2
# Shift all the elements between element 1
# element 2, right by 1.
while index != start:
arr[index] = arr[index - 1]
index -= 1
arr[start] = value
# Update all the pointers
start += 1
mid += 1
start2 += 1
"""
* l is for left index and r is right index of
the sub-array of arr to be sorted
"""
def mergeSort(arr, l, r):
if l < r:
# Same as (l + r) / 2, but avoids overflow
# for large l and r
m = l + (r - l) // 2
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m + 1, r)
merge(arr, l, m, r)
""" UTILITY FUNCTIONS """
""" Function to pran array """
def printArray(A, size):
for i in range(size):
print(A[i], end=" ")
print()
""" Driver program to test above functions """
if __name__ == "__main__":
arr = [12, 11, 13, 5, 6, 7]
arr_size = len(arr)
mergeSort(arr, 0, arr_size - 1)
printArray(arr, arr_size)