Tim Sort Algorithm
In this article, we will discuss the Tim sort Algorithm. Tim-sort is a sorting algorithm derived from insertion sort and merge sort. It was designed to perform optimally on different kind of real-world data.
Tim sort is an adaptive sorting algorithm that needs O(n log n) comparisons to sort an array of n elements. It was designed and implemented by Tim Peters in 2002 in a python programming language. It has been python's standard sorting algorithm since version 2.3. It is the fastest sorting algorithm.
The basic approach used in the Tim sort algorithm is - first sort small chunks by using the insertion sort and then merge all the big chunks using the merge function of the merge sort.
Now, let's see the algorithm of Tim sort.
Working of Tim sort Algorithm
Now, let's see the working of the Tim sort Algorithm.
In Tim sort, first the array is divided into small chunks that are known as RUN. After dividing, each individual RUN is taken, and sorted using the insertion sort technique. After that, all sorted RUNs are merged using the merge() function of the merge sort algorithm.
In Tim sort, the advantage of using the insertion sort is that insertion sort works efficiently for the array with small size.
Example of Tim sort Algorithm
Let's see the example of Tim sort algorithm. To understand the working of Tim sort algorithm, let's take an unsorted array. It will be easier to understand the Tim sort via an example.
Suppose the array elements are -
For the simple illustration, let's consider the size of RUN is 4.
Now, divide the given array into two sub-arrays that are -
The first sub-array is -
a = 10
a = 20
a = 42
The second sub-array is -
a = 25
a = 1
a = 19
Now, merge both sorted subarrays to get the final array as -
Now, the array is completely sorted.
Tim sort complexity
Now, let's see the time complexity of Tim sort in the best case, average case, and worst case. We will also see the space complexity of Tim sort.
1. Time Complexity
2. Space Complexity
Implementation of Tim sort
Now, let's see the programs of Tim sort in different programming languages.
Program: Write a program to implement Tim sort in C language.
After the execution of the above code, the output will be -
Program: Write a program to implement Tim sort in C++.
Program: Write a program to implement Tim sort in C#.
Program: Write a program to implement Tim sort in Java.
After the execution of above code, the output will be -
So, that's all about the article. Hope the article will be helpful and informative to you.
Next TopicLinear vs Non-Linear data structure