Skip to content

Commit f04331a

Browse files
author
Ian Doarn
authored
Merge pull request #100 from kgashok/master
iterative mergesort added
2 parents 07b5496 + 3f59acd commit f04331a

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

pygorithm/sorting/merge_sort.py

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,26 @@ def sort(_list):
4848
b = sort(_list[middle:])
4949
return merge(a, b)
5050

51+
from itertools import zip_longest
52+
def sorti(_list, verbose=True):
53+
"""
54+
Function to sort an array
55+
using merge sort algorithm, iteratively
56+
57+
:param _list: list of values to sort
58+
:return: sorted
59+
"""
60+
# breakdown every element into its own list
61+
series = [[i] for i in _list]
62+
while len(series) > 1:
63+
if verbose: print(series)
64+
# iterator to handle two at a time in the zip_longest below
65+
isl = iter(series)
66+
series = [
67+
merge(a, b) if b else a
68+
for a, b in zip_longest(isl, isl)
69+
]
70+
return series[0]
5171

5272
# TODO: Are these necessary?
5373
def time_complexities():
@@ -59,11 +79,13 @@ def time_complexities():
5979
return "Best Case: O(nlogn), Average Case: O(nlogn), Worst Case: O(nlogn)"
6080

6181

62-
def get_code():
82+
def get_code(iter=False):
6383
"""
6484
easily retrieve the source code
6585
of the sort function
6686
6787
:return: source code
6888
"""
89+
if iter:
90+
return inspect.getsource(sorti) + "\n"
6991
return inspect.getsource(sort) + "\n" + inspect.getsource(merge)

tests/test_sorting.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,13 @@ class TestMergeSort(unittest.TestCase, TestSortingAlgorithm):
116116
def sort(arr):
117117
return merge_sort.sort(arr)
118118

119+
class TestMergeSortIterative(unittest.TestCase, TestSortingAlgorithm):
120+
inplace = False
121+
alph_support = True
122+
123+
@staticmethod
124+
def sort(arr):
125+
return merge_sort.sorti(arr, verbose=False)
119126

120127
class TestQuickSort(unittest.TestCase, TestSortingAlgorithm):
121128
inplace = False

0 commit comments

Comments
 (0)