Skip to content

Commit 25566f6

Browse files
committed
TimSort.py finally approved
1 parent 6441406 commit 25566f6

1 file changed

Lines changed: 49 additions & 0 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
def InsertionSort(unsorted_list):
2+
for index in range(1, len(unsorted_list)):
3+
search_index = index
4+
insert_value = unsorted_list[index]
5+
while search_index > 0 and unsorted_list[search_index - 1] > insert_value:
6+
unsorted_list[search_index] = unsorted_list[search_index - 1]
7+
search_index -= 1
8+
unsorted_list[search_index] = insert_value
9+
return unsorted_list
10+
11+
12+
def Merge(first_sublist, second_sublist):
13+
i = j = 0
14+
merged_list = []
15+
16+
while i < len(first_sublist) and j < len(second_sublist):
17+
if first_sublist[i] < second_sublist[j]:
18+
merged_list.append(first_sublist[i])
19+
i += 1
20+
else:
21+
merged_list.append(second_sublist[j])
22+
j += 1
23+
while i < len(first_sublist):
24+
merged_list.append(first_sublist[i])
25+
i += 1
26+
while j < len(second_sublist):
27+
merged_list.append(second_sublist[j])
28+
j += 1
29+
return merged_list
30+
31+
32+
# combination of both insertion sort and merge sort
33+
def Tim_Sort(arr, run):
34+
for x in range(0, len(arr), run):
35+
arr[x : x + run] = InsertionSort(arr[x : x + run])
36+
runSize = run
37+
while runSize < len(arr):
38+
for x in range(0, len(arr), 2 * runSize):
39+
arr[x : x + 2 * runSize] = Merge(arr[x : x + runSize], arr[x + runSize : x + 2 * runSize])
40+
41+
runSize = runSize * 2
42+
43+
44+
45+
#Output of TimSort
46+
arr = [4, 6, 3, 9, 2, 8, 7, 5]
47+
run = 2
48+
Tim_Sort(arr, run)
49+
print(arr)

0 commit comments

Comments
 (0)