Count swaps required to sort an array using Insertion Sort

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: 4 Explanation:
Step 1: arr[0] stays in its initial position. Step 2: arr[1] shifts 1 place to the left. Count = 1. Step 3: arr[2] stays in its initial position. Step 4: arr[3] shifts 2 places to the left. Count = 2. Step 5: arr[5] 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++
Java
Python3
C#
Javascript
// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Stores the sorted// array elementsint temp[100000]; // Function to count the number of// swaps required to merge two sorted// subarray in a sorted formlong 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 arraylong 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 Codeint main(){    int A[] = { 2, 1, 3, 1, 2 };    int N = sizeof(A) / sizeof(A[0]);    cout << mergeInsertionSwap(A, 0, N - 1);    return 0;}
// Java program for the above approachimport 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 program to implement# the above approach # Stores the sorted# array elementstemp = [0] * 100000 # Function to count the number of# swaps required to merge two sorted# subarray in a sorted formdef 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 arraydef 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 Codeif __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# program for the above approachusing System;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  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.
<script>// javascript program of the above approach   // Stores the sorted  // array elements  let temp = new Array(100000).fill(0);    // Function to count the number of  // swaps required to merge two sorted  // subarray in a sorted form  function merge(A, left,                    mid, right)  {      // Stores the count of swaps    let swaps = 0;    let 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  function mergeInsertionSwap(A, left, right)  {    // Stores the total count    // of swaps required    let swaps = 0;    if (left < right)    {        // Find the middle index      // splitting the two halves      let 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             let A = [ 2, 1, 3, 1, 2 ];    let N = A.length;    document.write(mergeInsertionSwap(A, 0, N - 1)); // This code is contributed by target_2.</script>
4
 
Time Complexity: O(N * log(N))Auxiliary Space: O(N)
 
mohit kumar 29
susmitakundugoaldanga
code_hunt
target_2
array-merge
subarray
Technical Scripter 2020
Arrays
Recursion
Sorting
Technical Scripter
Arrays
Recursion
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Search, insert and delete in an unsorted array
Window Sliding Technique
Chocolate Distribution Problem
Move all negative numbers to beginning and positive to end with constant extra space
Write a program to print all permutations of a given string
Recursion
Program for Tower of Hanoi
Backtracking | Introduction
Print all subsequences of a string