-
Notifications
You must be signed in to change notification settings - Fork 682
/
Copy pathmerge_sort.py
68 lines (53 loc) · 1.64 KB
/
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
# Merge Sort implementation in Python with in depth comments
#
# Author: BedirT
# Merge Sort is a divide and conquer algorithm that divides the input array into two halves,
# calls itself for the two halves, and then merges the two sorted halves. The merge()
# function is used for merging two halves. The merge(arr, l, m, r) is key process that
# assumes that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one.
# Time Complexity: O(nlogn)
# Space Complexity: O(n)
def merge_sort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr) // 2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
merge_sort(L)
# Sorting the second half
merge_sort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i += 1
k += 1
while j < len(R):
arr[k] = R[j]
j += 1
k += 1
# Code to print the list
def print_list(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print("Given array is", end="\n")
print_list(arr)
merge_sort(arr)
print("Sorted array is: ", end="\n")
print_list(arr)