Count swaps required to sort an array using Insertion Sort | Stores the sorted array elements ; Function to count the number of swaps required to merge two sorted subarray in a sorted form ; Stores the count of swaps ; Function to count the total number of swaps required to sort the array ; Stores the total count of swaps required ; Find the middle index splitting the two halves ; Count the number of swaps required to sort the left subarray ; Count the number of swaps required to sort the right subarray ; Count the number of swaps required to sort the two sorted subarrays ; Driver Code
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 ) ) ;