Skip to content

Commit ec8aab9

Browse files
authored
Merge pull request prabhupant#66 from ThanasisMpalatsoukas/merge_sort
Created new sorting algorithm merge_sort
2 parents 9602a45 + 79b7776 commit ec8aab9

2 files changed

Lines changed: 51 additions & 1 deletion

File tree

algorithms/sorting/insertion_sort.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
High Level Description:
33
For every element in the given list, find its correct index by iterating
44
backwards and finding a slot. This forms a sorted array.
5-
65
Time Complexity:
76
Every element is visited, which contributes O(n). Swapping backwards takes
87
O(n/2) time on average, meaning that the total complexity is O(n^2)

algorithms/sorting/merge_sort.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
High level explanation:
3+
4+
mergeSort is a Divide and conquer algorithm that splits in halves the array and
5+
then builds it back up by merging and sorting at the same time its elements.
6+
7+
Time complexity:
8+
9+
mergeSort has a time complexity of O(n log n).
10+
"""
11+
12+
def mergeSort(arr):
13+
if len(arr) >1:
14+
mid = len(arr)//2 #Finding the mid of the array
15+
L = arr[:mid] # Dividing the array elements
16+
R = arr[mid:] # into 2 halves
17+
18+
mergeSort(L) # Sorting the first half
19+
mergeSort(R) # Sorting the second half
20+
21+
i = j = k = 0
22+
23+
# Copy data to temp arrays L[] and R[]
24+
while i < len(L) and j < len(R):
25+
if L[i] < R[j]:
26+
arr[k] = L[i]
27+
i+=1
28+
else:
29+
arr[k] = R[j]
30+
j+=1
31+
k+=1
32+
33+
# Checking if any element was left
34+
while i < len(L):
35+
arr[k] = L[i]
36+
i+=1
37+
k+=1
38+
39+
while j < len(R):
40+
arr[k] = R[j]
41+
j+=1
42+
k+=1
43+
44+
test_array = [10,30,20,100,40,80,90,210,34]
45+
46+
mergeSort(test_array)
47+
48+
print(test_array)
49+
50+
# This code is contributed by Mayank Khanna
51+
# and extented by thanasis mpalatsoukas

0 commit comments

Comments
 (0)