Open In App
Related Articles

Count swaps required to sort an array using Insertion Sort

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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[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++

// C++ Program to implement
// the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Stores the sorted
// array elements
int temp[100000];
 
// 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[0]);
    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[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.

                    

Javascript

<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>

                    

Output
4







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

New Apprpach:-  

Here’s an new approach:

1. The function `insertionSortSwaps` takes an array `arr` as input and initializes a variable `swaps` to keep track of the number of swaps.

2. It calculates the length of the array `arr` and stores it in the variable `n`.

3. The main loop runs from the second element (`i = 1`) to the last element (`n-1`) of the array. This loop iterates through each element and considers it as the key to be inserted into the sorted portion of the array.

4. Inside the loop, the current element is stored in the variable `key`. The variable `j` is set to `i – 1`, representing the index of the previous element.

5. The while loop checks if `j` is greater than or equal to 0 (to ensure we don’t go out of bounds) and if the element at index `j` is greater than the `key`. If both conditions are true, it means that the element at index `j` needs to be shifted to the right to make space for the `key` to be inserted.

6. Inside the while loop, the element at index `j` is moved to the right by assigning it to the next position `j + 1`. The variable `j` is decremented by 1, allowing us to compare the `key` with the previous element.

7. With each shift, the variable `swaps` is incremented by 1 to count the number of swaps performed during the sorting process.

8. Once the correct position for the `key` is found (either when the while loop condition becomes false or when `j` is less than 0), the `key` is inserted into the array at the position `j + 1`.

9. The outer loop continues to the next iteration, considering the next element as the `key` and repeating the process until all elements are in their correct sorted positions.

10. Finally, the function returns the total number of swaps (`swaps`) required to sort the array.

11. In the provided example, the array `[2, 1, 3, 1, 2]` is passed to the `insertionSortSwaps` function. The function sorts the array using Insertion Sort and counts the number of swaps. The result, `4`, is then printed.

Below is the implementation of the above approach:

C++

#include <iostream>
#include <vector>
using namespace std;
 
int insertionSortSwaps(vector<int>& arr) {
    int swaps = 0;
    int n = arr.size();
 
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i - 1;
 
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j -= 1;
            swaps += 1;
        }
 
        arr[j + 1] = key;
    }
 
    return swaps;
}
 
int main() {
    vector<int> arr = {2, 1, 3, 1, 2};
    int swaps = insertionSortSwaps(arr);
    cout << swaps << endl;
 
    return 0;
}

                    

Java

import java.util.ArrayList;
 
public class GFG {
 
    // Function to perform insertion sort and count swaps
    static int insertionSortSwaps(ArrayList<Integer> arr) {
        int swaps = 0;
        int n = arr.size();
 
        for (int i = 1; i < n; i++) {
            int key = arr.get(i);
            int j = i - 1;
 
            while (j >= 0 && arr.get(j) > key) {
                arr.set(j + 1, arr.get(j));
                j -= 1;
                swaps += 1;
            }
 
            arr.set(j + 1, key);
        }
 
        return swaps;
    }
 
    // Driver Code
    public static void main(String[] args) {
        ArrayList<Integer> arr = new ArrayList<>();
        arr.add(2);
        arr.add(1);
        arr.add(3);
        arr.add(1);
        arr.add(2);
 
        int swaps = insertionSortSwaps(arr);
        System.out.println(swaps);
    }
}

                    

Python3

def insertionSortSwaps(arr):
    swaps = 0
    n = len(arr)
 
    for i in range(1, n):
        key = arr[i]
        j = i - 1
 
        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1
            swaps += 1
 
        arr[j + 1] = key
 
    return swaps
 
arr = [2, 1, 3, 1, 2]
swaps = insertionSortSwaps(arr)
print(swaps)

                    

C#

using System;
 
class Program {
    static int InsertionSortSwaps(int[] arr)
    {
        int swaps
            = 0; // Initialize the swaps counter to zero
        int n = arr.Length; // Get the length of the input
                            // array
 
        // Start the loop from the second element, as the
        // first is considered sorted
        for (int i = 1; i < n; i++) {
            int key = arr[i]; // Store the current element
                              // to be inserted
            int j = i - 1; // Initialize j to the previous
                           // element's index
 
            // Compare elements and move them to the right
            // until the correct position is found
            while (j >= 0 && arr[j] > key) {
                arr[j + 1] = arr[j]; // Move the greater
                                     // element to the right
                j--; // Move left in the array
                swaps++; // Increment the swap count to
                         // track the number of swaps
            }
 
            arr[j + 1] = key; // Place the key in its
                              // correct sorted position
        }
 
        return swaps; // Return the total number of swaps
                      // performed
    }
 
    static void Main(string[] args)
    {
        int[] arr = { 2, 1, 3, 1, 2 };
        int swaps = InsertionSortSwaps(
            arr); // Call the sorting function
        Console.WriteLine(
            "Number of swaps: "
            + swaps); // Print the number of swaps
    }
}

                    

Javascript

// Function to perform insertion sort and count swaps
function insertionSortSwaps(arr) {
    let swaps = 0; // Initialize the swaps counter
    const n = arr.length; // Get the length of the input array
 
    // Iterate through the array starting from the second element
    for (let i = 1; i < n; i++) {
        const key = arr[i]; // Store the current element to be inserted
        let j = i - 1; // Initialize j to the previous element's index
 
        // Compare elements and move them to the right until the correct position is found
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j]; // Move the greater element to the right
            j--; // Move left in the array
            swaps++; // Increment the swap count to track the number of swaps
        }
 
        arr[j + 1] = key; // Place the key in its correct sorted position
    }
 
    return swaps; // Return the total number of swaps performed
}
 
// Main function
function main() {
    const arr = [2, 1, 3, 1, 2];
    const swaps = insertionSortSwaps(arr); // Call the sorting function
    console.log("Number of swaps:", swaps); // Print the number of swaps
}
 
main(); // Call the main function to execute the code

                    

Output
4








The time complexity:- of the provided `insertionSortSwaps` function is O(n^2), where n is the length of the input array.

The outer loop runs for n-1 iterations, as it starts from the second element (i=1) and goes up to the last element (n-1). Each iteration of the outer loop performs constant-time operations.

The inner while loop, in the worst-case scenario, iterates from j = i-1 down to j = 0. This loop compares the key with the elements in the sorted portion of the array and shifts the elements to the right. In the worst case, when the array is sorted in descending order, the while loop performs i comparisons for each i-th element in the array. Hence, the total number of comparisons becomes (n-1) + (n-2) + … + 1, which is approximately n^2/2. As a result, the time complexity of the inner loop is O(n^2).

Since the outer loop and the inner while loop are nested, the overall time complexity is dominated by the inner loop, resulting in O(n^2).

The auxiliary space:- of the `insertionSortSwaps` function is O(1) because it uses a constant amount of additional space. The space used does not depend on the size of the input array.


 



Last Updated : 08 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads