, , , (, ). Merge, , ( , ).
, , - , 2 ^ k , k.
, , - . , 2. .
.
[5, 7, 3, 4, 1, 9] → [5, 7] [3, 4] [1, 9] → [3, 4, 5, 7] [1, 9] → [1, 3, 4, 5, 7, 9]
[1, 9] - , , . , ( )
python:
from MergeSort import merge
def sort(arr):
n = len(arr) - 1
c = 1
start = 0
mid = 0
end = 0
while c <= n:
while end < n:
mid = start + c//2
end = start + c
if (start < n) and (end <= n):
merge(arr, start, mid, end)
start = end + 1
else:
merge(arr, start - c - 1, start-1, n)
c = 2*c + 1
start = 0
mid = 0
end = 0
I used the merge function from the regular (recursive) version. Although the above code is not the most elegant, it works and has the same complexity as the recursive version. (I did not check it completely, but it seems to me that it was so fast)
Here is the unit test:
def test_merge_sort_iterative(self):
for i in range(1, 100):
length = randint(10, 5000)
data = [randint(1, 10000) for x in range(1, length)]
IterativeMergeSort.sort(data)
issorted = True
i = 0
while (i < len(data) - 1) & issorted:
if data[i] > data[i + 1]:
issorted = False
i += 1
self.assertTrue(issorted, data)
return