×

Timsort Implementation Using C++

Timsort Implementation Using C++

The Timsort is a stable sorting algorithm that uses the idea of merge sort and insertion sort. It can also be called a hybrid algorithm of insertion and merge sort.  It is widely used in Java, Python, C, and C++ inbuilt sort algorithms. The idea behind this algorithm is to sort small chunks using insertion sort and then merge all the big chunks using the merge function of the merge sort algorithm.

Working

In this algorithm, the array is divided into small chunks. The chunks are known as RUN. Each RUN is taken and sorted using the insertion sort technique. After all the RUN are sorted, these are merged using the merge function. There may be a case where the size of the array can be less than RUN. In such a case, the array is sorted by the insertion sort technique. Usually, the RUN chunk varies from 32 to 64, depending on the size of the array. The merge function will only merge if the subarray chunk has the size of powers of 2.

The advantage of using insertion sort is because insertion sort works fine for the array with a small size.

Time complexity -

Best case - Omega(n)

Average case - O(nlogn)

Worst case - O(nlogn)

C++ code -

 #include<bits/stdc++.h>
 using namespace std;
 const int RUN = 32;  // Initialising the RUN to get chunks
 void insertionSort(int arr[], int left, int right) // Implementing insertion sort for RUN size chunks
 {
             for (int i = left + 1; i <= right; i++)
             {
                         int t = arr[i];
                         int j = i - 1;
                         while (j >= left &&  t < arr[j])
                         {
                                     arr[j+1] = arr[j--];
                         }
                         arr[j+1] = t;
             }
 }
 void merge(int arr[], int l, int m, int r) // using the merge function, the sorted chunks of size 32 are merged into one
 {
             int len1 = m - l + 1, len2 = r - m;
             int left[len1], right[len2]; 
             for (int i = 0; i < len1; i++)
                         left[i] = arr[l + i]; // Filling left array
             for (int i = 0; i < len2; i++)
                         right[i] = arr[m + 1 + i];  // Filling right array
             int i = 0;
             int j = 0;
             int k = l;
             while (i < len1 && j < len2)  // Iterate into both arrays left and right
             {
                         if (left[i] <= right[j]) // IF element in left is less then increment i by pushing into larger array
                         {
                                     arr[k] = left[i];
                                     i++;
                         }
                         else
                         {
                                     arr[k] = right[j];  // Element in right array is greater increment j
                                     j++;
                         }
                         k++;
             }
             while (i < len1) // This loop copies remaining element in left array
             {
                         arr[k] = left[i];
                         k++;
                         i++;
             }
             while (j < len2) // This loop copies remaining element in right array
             {
                         arr[k] = right[j];
                         k++;
                         j++;
             }
 }
 void timSortAlgo(int arr[], int n)
 {
             for (int i = 0; i < n; i+=RUN)           
 insertionSort(arr, i, min((i+31), (n-1)));  //Call insertionSort()
             for (int s = RUN; s < n; s = 2*s)     // Start merging from size RUN (or 32). It will continue upto 2*RUN
             {
                         // pick starting point of  left sub array. We  are going to merge  arr[left..left+size-1]
                         // and arr[left+size, left+2*size-1]
                         // After every merge, we
                         // increase left by 2*size
                         for (int left = 0; left < n;
                                                                                     left += 2*s)
                         {
                                     int mid = left + s - 1;             // find ending point of  left sub array  mid+1 is starting point  of right sub array
                                     int right = min((left + 2*s - 1), (n-1));
                                     merge(arr, left, mid, right); // merge sub array arr[left.....mid] &  arr[mid+1....right]
                         }
             }
 }
 void printArray(int arr[], int n)
 {
             for (int i = 0; i < n; i++)
                         cout << arr[i] << " ";
             cout << endl;
 }
 // Main function to implement timsort algorithm
 int main()
 {
             int arr[] = {-2, 7, 15, -14, 0, 15, 0, 7, -7,
                                                             -4, -13, 5, 8, -14, 12};
             int n = sizeof(arr)/sizeof(arr[0]);
 cout << "The Original array- ";
             printArray(arr, n);
             // calling the timsortAlgo function to sort array
             timSortAlgo(arr, n);
             cout<<"After Sorting Array Using TimSort Algorithm- ";
             printArray(arr, n);  // Calling print function
             return 0;
 } 

Related Topics

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

Binary Operator Overloading in C++

The Binary Operator Overloading in the C++ programming language will be covered in this part. An operator which comprises two operands to execute a mathematical operation is termed the Binary...

6 minutes read.

C++ Static

What is the Static keyword? In C++, the keyword static is used to give an element some particular properties. Static elements are only given storage in the static storage region once...

4 minutes read.

How to Handle Divide by Zero Exception in C++

If you are a programmer or interested in coding then it is obvious that you face some illogical test cases. Suppose, you have written one program that calculates the factorial...

6 minutes read.

C++ Program to Implement Merge Sort

C++ Program to Implement Merge Sort The technique of merge sort is based on the strategy of divide and conquer. We divide the set of while data into smaller bits, arranged...

3 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

C++ Continue in Do-while loop

Continue statement: Inside the loop, the continue statement is used to control the loop. C++ utilizes the continue keyword to implement the continue statement, which transfers the program's flow at the start...

4 minutes read.

List back () function in C++ STL

The list::back () function of the C++ STL returns a direct reference to the last element in the list container. This function varies from list::end (), which just returns an...

2 minutes read.

C++ array of Pointers

Array of Pointers: In high-level programming languages like C++, the array's name is its pointer. The name of an array contains an address which is the address of an element. In...

4 minutes read.

Nullptr in C++

What is Nullptr in C++? A null pointer value is represented by the term nullptr. Use a null pointer value to indicate that a native pointer type, inner pointer, or object...

3 minutes read.

Parameterize Constructor

C++ Parameterized Constructor A constructor having parameters is known as parameterize constructor. Parameterize constructor is used to assign different values. Syntax: className(data-type argument){   // Constructor definition   }   className(data-type argument, data-type argument){   // Constructor definition   } A parameterized constructor can be passed values to constructor function in two ways: 1)...

1 minute read.

Virtual class in C++

Introduction to Virtual Base class Virtual base classes can be utilized in virtual inheritance as a mechanism for examining many "instances" of a certain class while searching through multiple inheritances in...

6 minutes read.

Observer Design Pattern in C++

The Observer design pattern is a behavioural design pattern that allows an object (known as the subject) to notify other objects (known as observers) when its state changes. This is...

3 minutes read.

Use of Inheritance in C++

What is inheritance in c++? Inheritance is fundamental in object-oriented programming (OOP) languages like C++. It allows a programmer to create a new class (called a derived class) that inherits the...

4 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Top 5 IDEs for C++ That You Should Try Once

In the past decades, creating an application or interface from the very basic idea, the developer has to struggle a lot for it. Because an application is a combination of...

3 minutes read.

How to Declare Unordered Sets in C++

The implementation of an unordered set using a hash table ensures that the insertion is always randomised by hashing the keys into hash table indices. When we define keys of...

4 minutes read.

Array of Object in C++

What is an Array? In C++, an array is a group of related data types, such as int, char, float, double, etc., that are easily accessed by index value alone and...

12 minutes read.

Multiple Inheritance

C++ Multiple Inheritance Multiple inheritance is such an inheritance in which a derived class inherits properties of more than one base class.     C++ Multiple Inheritance Example In this example, two base classes Square and...

2 minutes read.

Converting string into integer in C++

When programming in C++, we'll frequently need to change one data type to another. When we use C++ to create apps, we must transform data from one type to another. When...

7 minutes read.