Related Articles

# Count swaps required to sort an array using Insertion Sort

• Difficulty Level : Medium
• Last Updated : 04 May, 2021

Given an array A[] of size N (1 ≤ N ≤ 105), the task is to calculate the number of swaps required to sort the array using insertion sort algorithm.

Examples:

Input: A[] = {2, 1, 3, 1, 2}
Output:
Explanation:

Step 1: arr stays in its initial position.
Step 2: arr shifts 1 place to the left. Count = 1.
Step 3: arr stays in its initial position.
Step 4: arr shifts 2 places to the left. Count = 2.
Step 5: arr shifts 1 place to its right. Count = 1.

Input: A[]={12, 15, 1, 5, 6, 14, 11}
Output: 10

Approach: The problem can be solved using Divide and Conquer Algorithm (Merge Sort). Follow the steps below to solve the problem:

• Split the array into two halves and recursively traverse both the halves.
• Sort each half and calculate the number of swaps required.
• Finally, print the total number of swaps required.

Below is the implementation of the above approach:

## C++

 `// C++ Program to implement``// the above approach` `#include ``using` `namespace` `std;` `// Stores the sorted``// array elements``int` `temp;` `// Function to count the number of``// swaps required to merge two sorted``// subarray in a sorted form``long` `int` `merge(``int` `A[], ``int` `left,``               ``int` `mid, ``int` `right)``{` `    ``// Stores the count of swaps``    ``long` `int` `swaps = 0;` `    ``int` `i = left, j = mid, k = left;` `    ``while` `(i < mid && j <= right) {` `        ``if` `(A[i] <= A[j]) {``            ``temp[k] = A[i];``            ``k++, i++;``        ``}``        ``else` `{``            ``temp[k] = A[j];``            ``k++, j++;``            ``swaps += mid - i;``        ``}``    ``}``    ``while` `(i < mid) {``        ``temp[k] = A[i];``        ``k++, i++;``    ``}` `    ``while` `(j <= right) {``        ``temp[k] = A[j];``        ``k++, j++;``    ``}` `    ``while` `(left <= right) {``        ``A[left] = temp[left];``        ``left++;``    ``}` `    ``return` `swaps;``}` `// Function to count the total number``// of swaps required to sort the array``long` `int` `mergeInsertionSwap(``int` `A[],``                            ``int` `left, ``int` `right)``{``    ``// Stores the total count``    ``// of swaps required``    ``long` `int` `swaps = 0;``    ``if` `(left < right) {` `        ``// Find the middle index``        ``// splitting the two halves``        ``int` `mid = left + (right - left) / 2;` `        ``// Count the number of swaps``        ``// required to sort the left subarray``        ``swaps += mergeInsertionSwap(A, left, mid);` `        ``// Count the number of swaps``        ``// required to sort the right subarray``        ``swaps += mergeInsertionSwap(A, mid + 1, right);` `        ``// Count the number of swaps required``        ``// to sort the two sorted subarrays``        ``swaps += merge(A, left, mid + 1, right);``    ``}``    ``return` `swaps;``}` `// Driver Code``int` `main()``{``    ``int` `A[] = { 2, 1, 3, 1, 2 };``    ``int` `N = ``sizeof``(A) / ``sizeof``(A);``    ``cout << mergeInsertionSwap(A, 0, N - 1);``    ``return` `0;``}`

## Java

 `// Java program for the above approach``import` `java.util.*;``class` `GFG``{` `  ``// Stores the sorted``  ``// array elements``  ``static` `int` `temp[] = ``new` `int``[``100000``];` `  ``// Function to count the number of``  ``// swaps required to merge two sorted``  ``// subarray in a sorted form``  ``static` `int` `merge(``int` `A[], ``int` `left,``                   ``int` `mid, ``int` `right)``  ``{` `    ``// Stores the count of swaps``    ``int` `swaps = ``0``;``    ``int` `i = left, j = mid, k = left;``    ``while` `(i < mid && j <= right)``    ``{``      ``if` `(A[i] <= A[j])``      ``{``        ``temp[k] = A[i];``        ``k++; i++;``      ``}``      ``else``      ``{``        ``temp[k] = A[j];``        ``k++; j++;``        ``swaps += mid - i;``      ``}``    ``}``    ``while` `(i < mid)``    ``{``      ``temp[k] = A[i];``      ``k++; i++;``    ``}` `    ``while` `(j <= right)``    ``{``      ``temp[k] = A[j];``      ``k++; j++;``    ``}` `    ``while` `(left <= right)``    ``{``      ``A[left] = temp[left];``      ``left++;``    ``}``    ``return` `swaps;``  ``}` `  ``// Function to count the total number``  ``// of swaps required to sort the array``  ``static` `int` `mergeInsertionSwap(``int` `A[],``                                ``int` `left, ``int` `right)``  ``{``    ``// Stores the total count``    ``// of swaps required``    ``int` `swaps = ``0``;``    ``if` `(left < right)``    ``{` `      ``// Find the middle index``      ``// splitting the two halves``      ``int` `mid = left + (right - left) / ``2``;` `      ``// Count the number of swaps``      ``// required to sort the left subarray``      ``swaps += mergeInsertionSwap(A, left, mid);` `      ``// Count the number of swaps``      ``// required to sort the right subarray``      ``swaps += mergeInsertionSwap(A, mid + ``1``, right);` `      ``// Count the number of swaps required``      ``// to sort the two sorted subarrays``      ``swaps += merge(A, left, mid + ``1``, right);``    ``}``    ``return` `swaps;``  ``}` `  ``// Driver code``  ``public` `static` `void` `main(String[] args)``  ``{``    ``int` `A[] = { ``2``, ``1``, ``3``, ``1``, ``2` `};``    ``int` `N = A.length;``    ``System.out.println(mergeInsertionSwap(A, ``0``, N - ``1``));``  ``}``}` `// This code is contributed by susmitakundugoaldanga.`

## Python3

 `# Python3 program to implement``# the above approach` `# Stores the sorted``# array elements``temp ``=` `[``0``] ``*` `100000` `# Function to count the number of``# swaps required to merge two sorted``# subarray in a sorted form``def` `merge(A, left, mid, right):``    ` `    ``# Stores the count of swaps``    ``swaps ``=` `0` `    ``i, j, k ``=` `left, mid, left``    ` `    ``while` `(i < mid ``and` `j <``=` `right):``        ` `        ``if` `(A[i] <``=` `A[j]):``            ``temp[k] ``=` `A[i]``            ``k, i ``=` `k ``+` `1``, i ``+` `1``        ``else``:``            ``temp[k] ``=` `A[j]``            ``k, j ``=` `k ``+` `1``, j ``+` `1``            ``swaps ``+``=` `mid ``-` `i` `    ``while` `(i < mid):``        ``temp[k] ``=` `A[i]``        ``k, i ``=` `k ``+` `1``, i ``+` `1` `    ``while` `(j <``=` `right):``        ``temp[k] ``=` `A[j]``        ``k, j ``=` `k ``+` `1``, j ``+` `1` `    ``while` `(left <``=` `right):``        ``A[left] ``=` `temp[left]``        ``left ``+``=` `1` `    ``return` `swaps` `# Function to count the total number``# of swaps required to sort the array``def` `mergeInsertionSwap(A, left, right):``    ` `    ``# Stores the total count``    ``# of swaps required``    ``swaps ``=` `0``    ` `    ``if` `(left < right):` `        ``# Find the middle index``        ``# splitting the two halves``        ``mid ``=` `left ``+` `(right ``-` `left) ``/``/` `2` `        ``# Count the number of swaps``        ``# required to sort the left subarray``        ``swaps ``+``=` `mergeInsertionSwap(A, left, mid)` `        ``# Count the number of swaps``        ``# required to sort the right subarray``        ``swaps ``+``=` `mergeInsertionSwap(A, mid ``+` `1``, right)` `        ``# Count the number of swaps required``        ``# to sort the two sorted subarrays``        ``swaps ``+``=` `merge(A, left, mid ``+` `1``, right)` `    ``return` `swaps` `# Driver Code``if` `__name__ ``=``=` `'__main__'``:``    ` `    ``A ``=` `[ ``2``, ``1``, ``3``, ``1``, ``2` `]``    ``N ``=` `len``(A)``    ` `    ``print` `(mergeInsertionSwap(A, ``0``, N ``-` `1``))` `# This code is contributed by mohit kumar 29`

## C#

 `// C# program for the above approach``using` `System;``class` `GFG``{` ` ``// Stores the sorted``  ``// array elements``  ``static` `int``[] temp = ``new` `int``;` `  ``// Function to count the number of``  ``// swaps required to merge two sorted``  ``// subarray in a sorted form``  ``static` `int` `merge(``int``[] A, ``int` `left,``                   ``int` `mid, ``int` `right)``  ``{` `    ``// Stores the count of swaps``    ``int` `swaps = 0;``    ``int` `i = left, j = mid, k = left;``    ``while` `(i < mid && j <= right)``    ``{``      ``if` `(A[i] <= A[j])``      ``{``        ``temp[k] = A[i];``        ``k++; i++;``      ``}``      ``else``      ``{``        ``temp[k] = A[j];``        ``k++; j++;``        ``swaps += mid - i;``      ``}``    ``}``    ``while` `(i < mid)``    ``{``      ``temp[k] = A[i];``      ``k++; i++;``    ``}` `    ``while` `(j <= right)``    ``{``      ``temp[k] = A[j];``      ``k++; j++;``    ``}` `    ``while` `(left <= right)``    ``{``      ``A[left] = temp[left];``      ``left++;``    ``}``    ``return` `swaps;``  ``}` `  ``// Function to count the total number``  ``// of swaps required to sort the array``  ``static` `int` `mergeInsertionSwap(``int``[] A,``                                ``int` `left, ``int` `right)``  ``{``    ` `    ``// Stores the total count``    ``// of swaps required``    ``int` `swaps = 0;``    ``if` `(left < right)``    ``{` `      ``// Find the middle index``      ``// splitting the two halves``      ``int` `mid = left + (right - left) / 2;` `      ``// Count the number of swaps``      ``// required to sort the left subarray``      ``swaps += mergeInsertionSwap(A, left, mid);` `      ``// Count the number of swaps``      ``// required to sort the right subarray``      ``swaps += mergeInsertionSwap(A, mid + 1, right);` `      ``// Count the number of swaps required``      ``// to sort the two sorted subarrays``      ``swaps += merge(A, left, mid + 1, right);``    ``}``    ``return` `swaps;``  ``}` `  ``// Driver Code``  ``static` `public` `void` `Main()``  ``{``    ``int``[] A = { 2, 1, 3, 1, 2 };``    ``int` `N = A.Length;``    ``Console.WriteLine(mergeInsertionSwap(A, 0, N - 1));``  ``}``}` `// This code is contributed by code_hunt.`

## Javascript

 ``
Output:
`4`

Time Complexity: O(N * log(N))
Auxiliary Space: O(N)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up