Skip to content

Commit d8315e7

Browse files
FrogBattlestokhos
authored andcommitted
Update tim_sort.py (TheAlgorithms#972)
* Update tim_sort.py Update tim_sort.py The previous algorithm was skipping numbers, according to issue TheAlgorithms#959, and my own tests. The version I am applying uses a while loop, which works correctly and is easier to compute, as there is no break statement. * Update tim_sort.py
1 parent d0d6145 commit d8315e7

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

sorts/tim_sort.py

+24-23
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,6 @@
1-
from __future__ import print_function
21
def binary_search(lst, item, start, end):
32
if start == end:
4-
if lst[start] > item:
5-
return start
6-
else:
7-
return start + 1
3+
return start if lst[start] > item else start + 1
84
if start > end:
95
return start
106

@@ -23,7 +19,7 @@ def insertion_sort(lst):
2319
for index in range(1, length):
2420
value = lst[index]
2521
pos = binary_search(lst, value, 0, index - 1)
26-
lst = lst[:pos] + [value] + lst[pos:index] + lst[index+1:]
22+
lst = lst[:pos] + [value] + lst[pos:index] + lst[index + 1 :]
2723

2824
return lst
2925

@@ -42,30 +38,34 @@ def merge(left, right):
4238

4339

4440
def tim_sort(lst):
45-
runs, sorted_runs = [], []
41+
"""
42+
>>> tim_sort("Python")
43+
['P', 'h', 'n', 'o', 't', 'y']
44+
>>> tim_sort((1.1, 1, 0, -1, -1.1))
45+
[-1.1, -1, 0, 1, 1.1]
46+
>>> tim_sort(list(reversed(list(range(7)))))
47+
[0, 1, 2, 3, 4, 5, 6]
48+
>>> tim_sort([3, 2, 1]) == insertion_sort([3, 2, 1])
49+
True
50+
>>> tim_sort([3, 2, 1]) == sorted([3, 2, 1])
51+
True
52+
"""
4653
length = len(lst)
54+
runs, sorted_runs = [], []
4755
new_run = [lst[0]]
4856
sorted_array = []
49-
50-
for i in range(1, length):
51-
if i == length - 1:
52-
new_run.append(lst[i])
53-
runs.append(new_run)
54-
break
55-
57+
i = 1
58+
while i < length:
5659
if lst[i] < lst[i - 1]:
57-
if not new_run:
58-
runs.append([lst[i - 1]])
59-
new_run.append(lst[i])
60-
else:
61-
runs.append(new_run)
62-
new_run = []
60+
runs.append(new_run)
61+
new_run = [lst[i]]
6362
else:
6463
new_run.append(lst[i])
64+
i += 1
65+
runs.append(new_run)
6566

6667
for run in runs:
6768
sorted_runs.append(insertion_sort(run))
68-
6969
for run in sorted_runs:
7070
sorted_array = merge(sorted_array, run)
7171

@@ -74,9 +74,10 @@ def tim_sort(lst):
7474

7575
def main():
7676

77-
lst = [5,9,10,3,-4,5,178,92,46,-18,0,7]
77+
lst = [5, 9, 10, 3, -4, 5, 178, 92, 46, -18, 0, 7]
7878
sorted_lst = tim_sort(lst)
7979
print(sorted_lst)
8080

81-
if __name__ == '__main__':
81+
82+
if __name__ == "__main__":
8283
main()

0 commit comments

Comments
 (0)