-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTim_sort.py
More file actions
42 lines (29 loc) · 962 Bytes
/
Copy pathTim_sort.py
File metadata and controls
42 lines (29 loc) · 962 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#divide it chunks and then each chunk should have a fixed size
#use insertion sort
#merge it and sort again if needed
#array to be entered by user
def insertion_sort(arr, left, right):
for i in range(left + 1, right + 1):
key = arr[i]
j = i - 1
while j >= left and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
def tim_sort(arr):
n = len(arr)
RUN = 4
for i in range(0, n, RUN):
insertion_sort(arr, i, min(i + RUN - 1, n - 1))
size = RUN
while size < n:
for left in range(0, n, 2 * size):
mid = min(left + size - 1, n - 1)
right = min(left + 2 * size - 1, n - 1)
if mid < right:
arr[left:right + 1] = sorted(arr[left:right + 1])
size *= 2
arr = list(map(int, input("Enter the array elements: ").split()))
print("Original array:", arr)
tim_sort(arr)
print("Sorted array:", arr)