Skip to content

Commit 1958cf2

Browse files
committed
added timsort.py
1 parent d3f3a88 commit 1958cf2

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

sorts/timsort.py

+68
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
def binary_search(the_array, item, start, end):
2+
if start == end:
3+
if the_array[start] > item:
4+
return start
5+
else:
6+
return start + 1
7+
if start > end:
8+
return start
9+
10+
mid = (start + end)/ 2
11+
if the_array[mid] < item:
12+
return binary_search(the_array, item, mid + 1, end)
13+
elif the_array[mid] > item:
14+
return binary_search(the_array, item, start, mid - 1)
15+
else:
16+
return mid
17+
18+
19+
"""
20+
Insertion sort that the heap sort uses if the array size is small or if
21+
the size of the "run" is small
22+
"""
23+
def insertion_sort(the_array):
24+
l = len(the_array)
25+
for index in range(1, l):
26+
value = the_array[index]
27+
pos = binary_search(the_array, value, 0, index - 1)
28+
the_array = the_array[:pos] + [value] + the_array[pos:index] + the_array[index+1:]
29+
return the_array
30+
31+
def merge(left, right):
32+
"""Takes two sorted lists and returns a single sorted list by comparing the
33+
elements one at a time.
34+
[1, 2, 3, 4, 5, 6]
35+
"""
36+
if not left:
37+
return right
38+
if not right:
39+
return left
40+
if left[0] < right[0]:
41+
return [left[0]] + merge(left[1:], right)
42+
return [right[0]] + merge(left, right[1:])
43+
44+
45+
def timsort(the_array):
46+
runs, sorted_runs = [], []
47+
l = len(the_array)
48+
new_run = [the_array[0]]
49+
for i in range(1, l):
50+
if i == l-1:
51+
new_run.append(the_array[i])
52+
runs.append(new_run)
53+
break
54+
if the_array[i] < the_array[i-1]:
55+
if not new_run:
56+
runs.append([the_array[i-1]])
57+
new_run.append(the_array[i])
58+
else:
59+
runs.append(new_run)
60+
new_run = []
61+
else:
62+
new_run.append(the_array[i])
63+
for each in runs:
64+
sorted_runs.append(insertion_sort(each))
65+
sorted_array = []
66+
for run in sorted_runs:
67+
sorted_array = merge(sorted_array, run)
68+
print(sorted_array)

0 commit comments

Comments
 (0)