Open In App

Count swaps required to sort an array using Insertion Sort

Last Updated : 03 Sep, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

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 Python C# JavaScript

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 Python C# JavaScript

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.


 



Next Article

Similar Reads

three90RightbarBannerImg