Last Updated : 26 Feb, 2025
Tim Sort is a hybrid sorting algorithm derived from merge sort and insertion sort. It is designed to perform well on many kinds of real-world data. Tim Sort's efficiency comes from its ability to exploit the structure present in the data, such as runs (consecutive sequences that are already ordered) and merges these runs using a modified merge sort approach. It was Created by Tim Peters in 2002, Tim Sort is the default sorting algorithm in Python and is renowned for its speed and efficiency in real-world data scenarios.
How Tim Sort Works?Why Tim Sort is Efficient?Let’s consider the following array as an example: arr[] = {4, 2, 8, 6, 1, 5, 9, 3, 7}.
Step 1: Define the size of the run
- Minimum run size: 32 (we’ll ignore this step since our array is small)
Step 2: Divide the array into runs
- In this step, we’ll use insertion sort to sort the small subsequences (runs) within the array.
- The initial array: [4, 2, 8, 6, 1, 5, 9, 3, 7]
- No initial runs are present, so we’ll create runs using insertion sort.
- Sorted runs: [2, 4], [6, 8], [1, 5, 9], [3, 7]
- Updated array: [2, 4, 6, 8, 1, 5, 9, 3, 7]
Step 3: Merge the runs
- In this step, we’ll merge the sorted runs using a modified merge sort algorithm.
- Merge the runs until the entire array is sorted.
- Merged runs: [2, 4, 6, 8], [1, 3, 5, 7, 9]
- Updated array: [2, 4, 6, 8, 1, 3, 5, 7, 9]
Step 4: Adjust the run size
- After each merge operation, we double the size of the run until it exceeds the length of the array.
- The run size doubles: 32, 64, 128 (we’ll ignore this step since our array is small)
Step 5: Continue merging
- Repeat the merging process until the entire array is sorted.
- Final merged run: [1, 2, 3, 4, 5, 6, 7, 8, 9]
The final sorted array is [1, 2, 3, 4, 5, 6, 7, 8, 9].
Tim Sort is the default sorting algorithm in Python's sort()
method for lists and sorted()
function. Here's how you can use it:
# Using the sort() method
a = [5, 3, 1, 4, 6, 2]
a.sort()
print("Sorted list using sort():", a)
# Using the sorted() function
a = [5, 3, 1, 4, 6, 2]
sorted_list = sorted(a)
print("Sorted list using sorted():", sorted_list)
Sorted list using sort(): [1, 2, 3, 4, 5, 6] Sorted list using sorted(): [1, 2, 3, 4, 5, 6]Complete Implementation of Time Sort in Python
The Tim Sort algorithm first divides the input array into smaller segments of size min_run and performs an insertion sort on each segment. It then starts merging the sorted segments, doubling the merge size in each iteration until the entire array is merged.
The key steps are:
- Initialize the minimum run size (min_run) to 32.
- Traverse the array in steps of min_run and perform insertion sort on each segment.
- Start merging the sorted segments, doubling the merge size in each iteration.
- Return the sorted array.
Code Example:
Python
def insertion_sort(arr, left=0, right=None):
# Base case: if the array is already sorted, do nothing
if right is None:
right = len(arr) - 1
# Iterate through the array, starting from the second element
for i in range(left + 1, right + 1):
# Select the current element
key_item = arr[i]
# Compare the current element with the previous one
j = i - 1
# While the previous element is greater than the current one,
# shift the previous element to the next position
while j >= left and arr[j] > key_item:
arr[j + 1] = arr[j]
j -= 1
# Once the loop ends, the previous element is less than or equal to
# the current element, so place the current element after it
arr[j + 1] = key_item
return arr
def merge(left, right):
# If the left subarray is empty, return the right subarray
if not left:
return right
# If the right subarray is empty, return the left subarray
if not right:
return left
# Compare the first elements of the two subarrays
if left[0] < right[0]:
# If the first element of the left subarray is smaller,
# recursively merge the left subarray with the right one
return [left[0]] + merge(left[1:], right)
else:
# If the first element of the right subarray is smaller,
# recursively merge the right subarray with the left one
return [right[0]] + merge(left, right[1:])
def tim_sort(arr):
# Initialize the minimum run size
min_run = 32
# Find the length of the array
n = len(arr)
# Traverse the array and do insertion sort on each segment of size min_run
for i in range(0, n, min_run):
insertion_sort(arr, i, min(i + min_run - 1, (n - 1)))
# Start merging from size 32 (or min_run)
size = min_run
while size < n:
# Divide the array into merge_size
for start in range(0, n, size * 2):
# Find the midpoint and endpoint of the left and right subarrays
midpoint = start + size
end = min((start + size * 2 - 1), (n - 1))
# Merge the two subarrays
merged_array = merge(arr[start:midpoint], arr[midpoint:end + 1])
# Assign the merged array to the original array
arr[start:start + len(merged_array)] = merged_array
# Increase the merge size for the next iteration
size *= 2
return arr
# Using the sorted() function
a = [5, 3, 1, 4, 6, 2]
sorted_list = tim_sort(a)
print("Sorted list using Tim Sort:", sorted_list)
Sorted list using Tim Sort: [1, 2, 3, 4, 5, 6]
Time complexity: O(n log n) in the average and worst cases, making it an efficient sorting algorithm for large input arrays.
Auxiliary space: O(n) as the algorithm needs to create new arrays to store the merged results during the merge step.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4