Skip to content

Commit 9fbe11a

Browse files
Merge pull request raviprakashdev#22 from qwertymaden/timsort
Added Timsort implementation in Python
2 parents 488a241 + 41d83b9 commit 9fbe11a

1 file changed

Lines changed: 41 additions & 0 deletions

File tree

TimSort.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
def timsort(array):
2+
min_run = 32
3+
n = len(array)
4+
5+
# Start by slicing and sorting small portions of the
6+
# input array. The size of these slices is defined by
7+
# your `min_run` size.
8+
for i in range(0, n, min_run):
9+
insertion_sort(array, i, min((i + min_run - 1), n - 1))
10+
11+
# Now you can start merging the sorted slices.
12+
# Start from `min_run`, doubling the size on
13+
# each iteration until you surpass the length of
14+
# the array.
15+
size = min_run
16+
while size < n:
17+
# Determine the arrays that will
18+
# be merged together
19+
for start in range(0, n, size * 2):
20+
# Compute the `midpoint` (where the first array ends
21+
# and the second starts) and the `endpoint` (where
22+
# the second array ends)
23+
midpoint = start + size - 1
24+
end = min((start + size * 2 - 1), (n-1))
25+
26+
# Merge the two subarrays.
27+
# The `left` array should go from `start` to
28+
# `midpoint + 1`, while the `right` array should
29+
# go from `midpoint + 1` to `end + 1`.
30+
merged_array = merge(
31+
left=array[start:midpoint + 1],
32+
right=array[midpoint + 1:end + 1])
33+
34+
# Finally, put the merged array back into
35+
# your array
36+
array[start:start + len(merged_array)] = merged_array
37+
38+
# Each iteration should double the size of your arrays
39+
size *= 2
40+
41+
return array

0 commit comments

Comments
 (0)