-
Notifications
You must be signed in to change notification settings - Fork 111
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #30 from anubhav823/MergeSort
Added MergeSort
- Loading branch information
Showing
1 changed file
with
37 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
|
||
# -*- coding: utf-8 -*- | ||
def mergeSort(array): | ||
if len(array)>1: | ||
|
||
#dividing array into 2 parts | ||
middle=len(array)//2 | ||
leftArray=array[:middle] | ||
rightArray=array[middle:] | ||
|
||
#recursively calling MergeSort | ||
mergeSort(leftArray) | ||
mergeSort(rightArray) | ||
|
||
#3 variables for copying the sorted values into final array | ||
i=j=k=0 | ||
#copying into final array | ||
while i<len(leftArray) and j<len(rightArray): | ||
if leftArray[i]<rightArray[j]: | ||
array[k]=leftArray[i] | ||
i+=1 | ||
else: | ||
array[k]=rightArray[j] | ||
j+=1 | ||
k+=1 | ||
|
||
#checking for any elements still left | ||
while i<len(leftArray): | ||
array[k]=leftArray[i] | ||
i+=1 | ||
k+=1 | ||
|
||
while j<len(rightArray): | ||
array[k]=rightArray[j] | ||
j+=1 | ||
k+=1 | ||
|