From 0ceb5f104fabc0279a06306047fb8fd5bb3161a8 Mon Sep 17 00:00:00 2001 From: JacksonMateus <48231382+JacksonMateus@users.noreply.github.com> Date: Fri, 18 Oct 2019 16:44:46 -0300 Subject: [PATCH] Create timSort.py --- allalgorithms/sorting/timSort.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 allalgorithms/sorting/timSort.py diff --git a/allalgorithms/sorting/timSort.py b/allalgorithms/sorting/timSort.py new file mode 100644 index 0000000..f2405bc --- /dev/null +++ b/allalgorithms/sorting/timSort.py @@ -0,0 +1,23 @@ +def timsort(the_array): + runs, sorted_runs = [], [] + l = len(the_array) + new_run = [the_array[0]] + for i in range(1, l): + if i == l-1: + new_run.append(the_array[i]) + runs.append(new_run) + break + if the_array[i] < the_array[i-1]: + if not new_run: + runs.append([the_array[i-1]]) + new_run.append(the_array[i]) + else: + runs.append(new_run) + new_run = [] + else: + new_run.append(the_array[i]) + for each in runs: + sorted_runs.append(insertion_sort(each)) + sorted_array = [] + for run in sorted_runs: + sorted_array = merge(sorted_array, run)