Created
September 27, 2021 16:40
-
-
Save mkhuzaima/df0ccf86a9f36611250f4d0aec41d586 to your computer and use it in GitHub Desktop.
Python code for merge sort algorithm for sorting n numbers. The running time of this algorithm is: O(n . lg(n) )
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def merge(arr, start, middle, end): | |
i = j = 0 | |
k = start | |
left = arr[start:middle] | |
right = arr[middle:end] | |
while i < len(left) and j < len(right): | |
if left[i] < right[j]: | |
arr[k] = left[i] | |
i += 1 | |
else: | |
arr[k] = right[j] | |
j+= 1 | |
k += 1 | |
while i < len(left): | |
arr[k] = left[i] | |
i += 1 | |
k += 1 | |
while j < len(right): | |
arr[k] = right[j] | |
j += 1 | |
k += 1 | |
def mergeSort(arr, end, start = 0): | |
if end == start +1: | |
return arr[start] | |
middle = (start + end) // 2 | |
mergeSort(arr, middle, start) | |
mergeSort(arr, end, middle) | |
merge(arr, start, middle, end) | |
size = int(input('Enter the size of the array: ')) | |
arr = [] | |
for i in range(size): | |
element = int(input(f'Enter the number {i + 1}: ')) | |
arr.append(element) | |
print("The unsorted array is : " + str(arr)) | |
mergeSort(arr, size) | |
print("The sorted array is : " + str(arr)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment