Skip to content

Instantly share code, notes, and snippets.

@rounakdatta
Last active November 15, 2020 11:10
Show Gist options
  • Save rounakdatta/8e7dbf6111010c4c78351c24f0bc0eef to your computer and use it in GitHub Desktop.
Save rounakdatta/8e7dbf6111010c4c78351c24f0bc0eef to your computer and use it in GitHub Desktop.
Multithreaded Merge Sort
import _thread
from threading import Thread
class MergeSorter:
def merge(self, left, right, myArray):
i = 0
j = 0
k = 0
while i < len(left) and j < len(right):
if (left[i] < right[i]):
myArray[k] = left[i]
i += 1
else:
myArray[k] = right[j]
j += 1
k += 1
# remaining
while i < len(left):
myArray[k] = left[i]
i += 1
k += 1
while j < len(right):
myArray[k] = right[j]
j += 1
k += 1
def mergeSort(self, myArray):
left = []
right = []
n = len(myArray)
if n < 2:
return
mid = n // 2
for i in range(mid):
left.append(myArray[i])
for i in range(mid, n):
right.append(myArray[i])
print(left, right)
#thread1 = _thread.start_new_thread(self.mergeSort, (left,)) #mergeSort(left)
#thread2 = _thread.start_new_thread(self.mergeSort, (right,)) #mergeSort(right)
thread1 = Thread(target=self.mergeSort, args=(left,))
thread2 = Thread(target=self.mergeSort, args=(right,))
thread1.start()
thread1.join()
thread2.start()
thread2.join()
self.merge(left, right, myArray)
foo = MergeSorter()
myArray = [4, 3, 2, 1]
foo.mergeSort(myArray)
while True:
print(myArray)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment