-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmergesort.py
84 lines (69 loc) · 2.51 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import time
max_time = 0.250
swapCount = 0
##---to reset swap count
def mergeSort(arr,displayArray,speedInput,pauseBool,start,end):
global swapCount
swapCount = 0
merge_sort(arr,displayArray,speedInput,pauseBool,start,end)
# divides the array recursively into two parts then sorts
def merge_sort(arr,displayArray,speedInput,pauseBool,start,end):
if start<end:
mid = (start+end) // 2
merge_sort(arr,displayArray,speedInput,pauseBool,start,mid)
merge_sort(arr,displayArray,speedInput,pauseBool,mid+1,end)
merge(arr,displayArray,speedInput,pauseBool,start,mid,end)
def merge(arr,displayArray,speedInput,pauseBool,start,mid,end):
global swapCount
#--highlight the left and the right parts of the array
colorArray = []
for i in range(len(arr)):
if i>=start and i<=mid:
colorArray.append('#ffff00')
elif i>=mid+1 and i<=end:
colorArray.append('#5200cc')
else:
colorArray.append('red')
displayArray(arr,colorArray,swapCount)
time.sleep(max_time - (speedInput * max_time / 100))
arrL = arr[start:mid+1]
arrR = arr[mid+1:end+1]
i, j, k = 0, 0,start # i->arrL; j->arrR; k->arr
while (i < len(arrL) and j < len(arrR)):
if arrL[i] < arrR[j]:
arr[k] = arrL[i]
swapCount+=1
i+=1
for x in range(start,k):
colorArray[x] = 'green'
displayArray(arr, colorArray, swapCount)
time.sleep(max_time - (speedInput * max_time / 100))
else:
arr[k] = arrR[j]
swapCount+=1
j+=1
for x in range(start,k):
colorArray[x] = 'green'
displayArray(arr, colorArray, swapCount)
time.sleep(max_time - (speedInput * max_time / 100))
k+=1
#check if anything left
while i<len(arrL):
arr[k] = arrL[i]
i += 1
k += 1
swapCount+=1
for x in range(start, k ):
colorArray[x] = 'green'
displayArray(arr, colorArray, swapCount)
time.sleep(max_time - (speedInput * max_time / 100))
while j<len(arrR):
arr[k] = arrR[j]
j += 1
k += 1
swapCount+=1
for x in range(start, k ):
colorArray[x] = 'green'
displayArray(arr, colorArray, swapCount)
time.sleep(max_time - (speedInput * max_time / 100))
print("Sorted arr : ",arr)