chore(Python): added Merge Sort algorithm (#329)
Co-authored-by: Sumanth <sumanthpalla05@gmail.com> Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com>pull/346/head
parent
bd71d9d805
commit
fd43c38320
|
@ -38,6 +38,7 @@
|
||||||
6. [Heap Sort](sorting/heap-sort.py)
|
6. [Heap Sort](sorting/heap-sort.py)
|
||||||
7. [Radix Sort](sorting/radix-sort.py)
|
7. [Radix Sort](sorting/radix-sort.py)
|
||||||
8. [Shell Sort](sorting/shell-sort.py)
|
8. [Shell Sort](sorting/shell-sort.py)
|
||||||
|
9. [Merge sort](sorting/merge_sort.py)
|
||||||
|
|
||||||
## Strings
|
## Strings
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,34 @@
|
||||||
|
## Implementation of merge sort
|
||||||
|
## Merge Sort is a recursive algorithm which sorts the list by divide and conquer approach
|
||||||
|
def merge_sort(list):
|
||||||
|
# if list size <= 1, the list is anyway sorted! :)
|
||||||
|
if len(list)==1: return list
|
||||||
|
#splitting the list into half
|
||||||
|
mid = len(list)//2 # integer division
|
||||||
|
l = list[:mid]
|
||||||
|
r = list[mid:]
|
||||||
|
merge_sort(l) # recursive calling of left part of list
|
||||||
|
merge_sort(r) # recursive calling of right part of list
|
||||||
|
#merging the left and right parts
|
||||||
|
i=j=k=0
|
||||||
|
while(i<len(l)and j<len(r)):
|
||||||
|
if l[i]<=r[j]:
|
||||||
|
list[k]=l[i]
|
||||||
|
i+=1
|
||||||
|
else:
|
||||||
|
list[k]=r[j]
|
||||||
|
j+=1
|
||||||
|
k+=1
|
||||||
|
while(i<len(l)):
|
||||||
|
list[k]=l[i]
|
||||||
|
i+=1
|
||||||
|
k+=1
|
||||||
|
while(j<len(r)):
|
||||||
|
list[k]=r[j]
|
||||||
|
j+=1
|
||||||
|
k+=1
|
||||||
|
return list
|
||||||
|
##### main ###
|
||||||
|
if __name__ == '__main__':
|
||||||
|
arr = [10, 1, 6, 256, 2, 53, 235, 53, 1, 7, 0, -23, 23]
|
||||||
|
print("Sorted Array:", merge_sort(arr))
|
Loading…
Reference in New Issue