Algorithms-and-Data-Structures/Python-Merge-Sort/mergesort.py
2024-05-02 20:14:36 +01:00

39 lines
879 B
Python

def mergeSort(array):
length = len(array)
if length <= 1: return
middle = length // 2
leftArray = array[:middle]
rightArray = array[middle:]
mergeSort(leftArray)
mergeSort(rightArray)
merge(leftArray, rightArray, array)
def merge(leftArray, rightArray, array):
leftLength = len(leftArray)
rightLength = len(rightArray)
i = 0
l = 0
r = 0
while l < leftLength and r < rightLength:
if leftArray[l] < rightArray[r]:
array[i] = leftArray[l]
l += 1
else:
array[i] = rightArray[r]
r += 1
i += 1;
if l < leftLength:
array[i] = leftArray[l]
if __name__ == '__main__':
arr = [12, 11, 5, 6, 7, 194]
print(f'Given array is: \n{arr}');
mergeSort(arr);
print(f'Sorted array is: \n{arr}')