-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathDivideAndConquer-mergeSort.py
52 lines (42 loc) · 1.19 KB
/
DivideAndConquer-mergeSort.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
def merge_sort(Arr,start,end):
if(start<end):
mid = (start+end)//2 #Computes floor of middle value
merge_sort(Arr,start,mid)
merge_sort(Arr,mid+1,end)
merge(Arr,start, mid, end)
def merge(Arr, start, mid, end):
#temporary arrays to copy the elements of subarray
leftArray_size = (mid-start)+1
rightArray_size = (end-mid)
leftArray = [0]*leftArray_size
rightArray = [0]*rightArray_size
for i in range(0, leftArray_size):
leftArray[i] = Arr[start+i]
for i in range(0, rightArray_size):
rightArray[i] = Arr[mid+1+i]
i=0
j=0
k=start
while (i < leftArray_size and j < rightArray_size):
if (leftArray[i] < rightArray[j]):
# filling the original array with the smaller element
Arr[k] = leftArray[i]
i = i+1
else:
# filling the original array with the smaller element
Arr[k] = rightArray[j]
j = j+1
k = k+1
# copying remaining elements if any
while (i<leftArray_size):
Arr[k] = leftArray[i]
k = k+1
i = i+1
while (j<rightArray_size):
Arr[k] = rightArray[j]
k = k+1
j = j+1
if __name__ == '__main__':
Arr = [2,14,1,9,10,5,6,18,11]
merge_sort(Arr, 0, 8)
print(Arr)