Timsort is a hybrid sorting algorithm derived from Merge Sort and Insertion Sort. It was designed to take advantage of real-world data patterns — specifically, partially sorted arrays. Timsort finds and optimizes “runs” (small sorted sequences) in the data and then merges them efficiently.
Arrays.sort(Object[])Collections.sort(List<T>)| Java API | Internal Algorithm |
|---|---|
Arrays.sort(Object[]) | Timsort |
Collections.sort(List) | Timsort |
Note:
Arrays.sort(int[])uses Dual-Pivot Quicksort for primitives.
| Case | Time Complexity |
|---|---|
| Best | O(n) |
| Average | O(n log n) |
| Worst | O(n log n) |
import java.util.*;
public class TimsortExample {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(
42, 20, 17, 13, 28, 14, 23, 15
));
System.out.println("Original list:");
System.out.println(numbers);
// Timsort is used internally by Collections.sort()
Collections.sort(numbers);
System.out.println("Sorted list:");
System.out.println(numbers);
}
}
Original list:
[42, 20, 17, 13, 28, 14, 23, 15]
Sorted list:
[13, 14, 15, 17, 20, 23, 28, 42]
Let’s sort this list:
[42, 20, 17, 13, 28, 14, 23, 15]
Timsort scans and identifies “runs” — sequences already in order:
Now we have 3 ascending runs:
[13, 17, 20, 42], [14, 28], [15, 23]
If runs are too small (e.g. < 32), Insertion Sort may be used to grow them.
Timsort merges the sorted runs similar to Merge Sort:
[13, 14, 15, 17, 20, 23, 28, 42]
Collections.sort() and Arrays.sort(Object[]).