×

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

C++ Void Pointer

A void pointer is a general purpose pointer that can have an address of any data type but is not related to any data type. Void Pointer Syntax: void *ptr;  We can't...

2 minutes read.

Top best IDEs for C/C++ Developers in 2024

Nothing in the current digital world is conceivable without programming. Everything needs programming, from the cell phones in our pockets to self-driving cars. Programming is also necessary for the mouse...

9 minutes read.

C++ 11 vs C++ 14 vs C++ 17

C++ is a language that is used to create a high-performance application. C++ 11, C++ 14, and C++ 17 are the different version of C++. There are some differences between...

1 minute read.

How to run program in turbo c++

What is Turbo C++? Turbo c++ is an integrated development environment (IDE) and a compiler to run C++ code. Turbo c++ helps to link the header files with the main code....

2 minutes read.

Armstrong Number using Do-While Loop in C++

What is Do-While Loop? An iterative loop that checks the condition at the end.The Do-While loop can be used whenever a test condition is specific, as the control enters the loop...

4 minutes read.

C++ Prime number program

In this lesson, you'll learn how to verify whether a given number is a prime number or not in C++, and you'll obtain code to do it. What is the definition...

3 minutes read.

C++ Writing to file

In file handling, write() function is used to write data into the file. The write() uses ofstream or fstream library to write into the file. Syntax file-stream-class   file-stream-object;   file-stream-object.write((char *)&var , sizeof (var)); The write() takes two arguments. The first argument is the address of variable var...

2 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

C++ Program to find the product array puzzle

Write a C++ program to form a product array from arr[] where product[i] is the product of all the array elements except arr[i]. Example Input: arr[]  = {10, 3, 5, 6,...

6 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

Preventing Object Copy in C++

C++ is an object-oriented programming language that provides the ability to create objects, define class and pass objects to functions. When passing an object to a function or returning an...

7 minutes read.

Ways to Copy a Vector in C++

Vectors in C++ are the same as arrays, along with additional outstanding features than them, like array lists in Java programming language. In Vectors, the size constraint is eliminated, which...

5 minutes read.

C++ Virtual Function

A virtual function is such function which is declared inside the base class and redefined by the derive class. C++ uses a virtual keyword to make a function as a virtual function. The virtual...

1 minute read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

Iostream in C++

Using Iostream in C++, we can perform input and output operation capabilities. This represents input and output, and the stream is used to carry out this capability. A stream is...

4 minutes read.

Convex hull Algorithm in C++

The intersection of all convex sets containing a certain subset of a Euclidean space, or alternatively, the set of all convex combinations of points in the subset, defines the convex...

4 minutes read.

C++ Installation

Let's install C++ setup to start programming in C++. C++ setup contains C++ compiler which is required in your system. There are lots of C++ compilers available, you must choose...

1 minute read.

C++ Socket Programming

In this world, computer networking has become very important for sharing of data. Every good programmer has some knowledge about computer networking. Socket programming is one of the critical topics...

6 minutes read.

Program to convert infix to postfix expression in C++

Parentheses are frequently employed in mathematical formulas to make their interpretation easier to understand. However, with computers, parenthesis in an expression might lengthen the time it takes to find a...

7 minutes read.

Single dimension array

C++ Array An array is a collection of data (elements) of the same data types. The elements of an array are allocated in contiguous memory allocation. Elements of the array are accessed through...

1 minute read.