Count swaps required to sort an array using Insertion Sort
Last Updated :
08 Oct, 2023
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++
#include <bits/stdc++.h>
using namespace std;
int temp[100000];
long int merge( int A[], int left,
int mid, int right)
{
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;
}
long int mergeInsertionSwap( int A[],
int left, int right)
{
long int swaps = 0;
if (left < right) {
int mid = left + (right - left) / 2;
swaps += mergeInsertionSwap(A, left, mid);
swaps += mergeInsertionSwap(A, mid + 1, right);
swaps += merge(A, left, mid + 1, right);
}
return swaps;
}
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
import java.util.*;
class GFG
{
static int temp[] = new int [ 100000 ];
static int merge( int A[], int left,
int mid, int right)
{
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;
}
static int mergeInsertionSwap( int A[],
int left, int right)
{
int swaps = 0 ;
if (left < right)
{
int mid = left + (right - left) / 2 ;
swaps += mergeInsertionSwap(A, left, mid);
swaps += mergeInsertionSwap(A, mid + 1 , right);
swaps += merge(A, left, mid + 1 , right);
}
return swaps;
}
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 ));
}
}
|
Python3
temp = [ 0 ] * 100000
def merge(A, left, mid, right):
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
def mergeInsertionSwap(A, left, right):
swaps = 0
if (left < right):
mid = left + (right - left) / / 2
swaps + = mergeInsertionSwap(A, left, mid)
swaps + = mergeInsertionSwap(A, mid + 1 , right)
swaps + = merge(A, left, mid + 1 , right)
return swaps
if __name__ = = '__main__' :
A = [ 2 , 1 , 3 , 1 , 2 ]
N = len (A)
print (mergeInsertionSwap(A, 0 , N - 1 ))
|
C#
using System;
class GFG
{
static int [] temp = new int [100000];
static int merge( int [] A, int left,
int mid, int right)
{
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;
}
static int mergeInsertionSwap( int [] A,
int left, int right)
{
int swaps = 0;
if (left < right)
{
int mid = left + (right - left) / 2;
swaps += mergeInsertionSwap(A, left, mid);
swaps += mergeInsertionSwap(A, mid + 1, right);
swaps += merge(A, left, mid + 1, right);
}
return swaps;
}
static public void Main()
{
int [] A = { 2, 1, 3, 1, 2 };
int N = A.Length;
Console.WriteLine(mergeInsertionSwap(A, 0, N - 1));
}
}
|
Javascript
<script>
let temp = new Array(100000).fill(0);
function merge(A, left,
mid, right)
{
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 mergeInsertionSwap(A, left, right)
{
let swaps = 0;
if (left < right)
{
let mid = left + (right - left) / 2;
swaps += mergeInsertionSwap(A, left, mid);
swaps += mergeInsertionSwap(A, mid + 1, right);
swaps += merge(A, left, mid + 1, right);
}
return swaps;
}
let A = [ 2, 1, 3, 1, 2 ];
let N = A.length;
document.write(mergeInsertionSwap(A, 0, N - 1));
</script>
|
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 {
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;
}
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;
int n = arr.Length;
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--;
swaps++;
}
arr[j + 1] = key;
}
return swaps;
}
static void Main( string [] args)
{
int [] arr = { 2, 1, 3, 1, 2 };
int swaps = InsertionSortSwaps(
arr);
Console.WriteLine(
"Number of swaps: "
+ swaps);
}
}
|
Javascript
function insertionSortSwaps(arr) {
let swaps = 0;
const n = arr.length;
for (let i = 1; i < n; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
swaps++;
}
arr[j + 1] = key;
}
return swaps;
}
function main() {
const arr = [2, 1, 3, 1, 2];
const swaps = insertionSortSwaps(arr);
console.log( "Number of swaps:" , swaps);
}
main();
|
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.
Share your thoughts in the comments
Please Login to comment...