Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 2 additions & 20 deletions Python/Tim_Sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,6 @@
def insertion_sort(arr, left, right):
"""
Perform insertion sort on a subarray from index 'left' to 'right'.

Args:
arr (list): The list to be sorted.
left (int): The starting index of the subarray.
right (int): The ending index of the subarray.
"""
for i in range(left + 1, right + 1):
key_item = arr[i]
Expand All @@ -20,12 +15,6 @@ def insertion_sort(arr, left, right):
def merge(arr, left, mid, right):
"""
Merge two sorted subarrays into a single sorted array.

Args:
arr (list): The original array with two sorted subarrays.
left (int): The starting index of the left subarray.
mid (int): The ending index of the left subarray and middle point.
right (int): The ending index of the right subarray.
"""
left_part = arr[left:mid + 1]
right_part = arr[mid + 1:right + 1]
Expand All @@ -43,7 +32,6 @@ def merge(arr, left, mid, right):
j += 1
k += 1


while i < len(left_part):
arr[k] = left_part[i]
i += 1
Expand All @@ -57,19 +45,12 @@ def merge(arr, left, mid, right):
def tim_sort(arr):
"""
Perform TimSort on the input array.

TimSort is a hybrid sorting algorithm derived from merge sort and insertion sort. It sorts smaller chunks using insertion sort, then merges them using a merge sort.

Args:
arr (list): The list to be sorted.
"""
n = len(arr)


for start in range(0, n, MIN_RUN):
end = min(start + MIN_RUN - 1, n - 1)
insertion_sort(arr, start, end)


size = MIN_RUN
while size < n:
Expand All @@ -86,7 +67,7 @@ def tim_sort(arr):
if __name__ == "__main__":
def test_tim_sort():
test_cases = [
([12, 11, 13, 5, 6, 7], [5, 6, 7, 11, 12, 13]), # Random order
([12, 11, 13, 5, 6, 7], [5, 6, 7, 11, 12, 13]), # Random order
([], []), # Empty array
([1], [1]), # Single element
([3, 1, 2], [1, 2, 3]), # Small array
Expand All @@ -101,3 +82,4 @@ def test_tim_sort():
print(f"Test case {i+1} passed.")

test_tim_sort()