Skip to content

Commit dad781d

Browse files
authored
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.
1 parent 2b36528 commit dad781d

File tree

1 file changed

+10
-20
lines changed

1 file changed

+10
-20
lines changed

sorts/tim_sort.py

Lines changed: 10 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -42,36 +42,26 @@ def merge(left, right):
4242

4343

4444
def tim_sort(lst):
45-
runs, sorted_runs = [], []
46-
length = len(lst)
47-
new_run = [lst[0]]
48-
sorted_array = []
49-
50-
for i in range(1, length):
51-
if i == length - 1:
52-
new_run.append(lst[i])
45+
length=len(lst)
46+
runs,sorted_runs=[], []
47+
new_run=[lst[0]]
48+
sorted_array=[]
49+
i=1
50+
while i<length:
51+
if lst[i]<lst[i-1]:
5352
runs.append(new_run)
54-
break
55-
56-
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 = []
53+
new_run=[lst[i]]
6354
else:
6455
new_run.append(lst[i])
56+
i+=1
57+
runs.append(new_run)
6558

6659
for run in runs:
6760
sorted_runs.append(insertion_sort(run))
68-
6961
for run in sorted_runs:
7062
sorted_array = merge(sorted_array, run)
7163

7264
return sorted_array
73-
74-
7565
def main():
7666

7767
lst = [5,9,10,3,-4,5,178,92,46,-18,0,7]

0 commit comments

Comments
 (0)