Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Tim Sort Algorithms
The main idea behind Tim Sort is to exploit the existing order in the data to minimize the number of comparisons and swaps. It achieves this by dividing the array into small subarrays called runs, which are already sorted, and then merging these runs using a modified merge sort algorithm.
How does Tim Sort work?
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].