Minimum number of swaps required to minimize sum of absolute differences between adjacent array elements | Comparator to sort in the descending order ; Function to find the minimum number of swaps required to sort the array in increasing order ; Stores the array elements with its index ; Sort the array in the increasing order ; Keeps the track of visited elements ; Stores the count of swaps required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of nodes in this cycle ; Update the value of j ; Move to the next element ; Increment cycle_size ; Update the ans by adding current cycle ; Function to find the minimum number of swaps required to sort the array in decreasing order ; Stores the array elements with its index ; Sort the array in the descending order ; Keeps track of visited elements ; Stores the count of resultant swap required ; Traverse array elements ; If the element is already swapped or at correct position ; Find out the number of node in this cycle ; Update the value of j ; Move to the next element ; Increment the cycle_size ; Update the ans by adding current cycle size ; Function to find minimum number of swaps required to minimize the sum of absolute difference of adjacent elements ; Sort in ascending order ; Sort in descending order ; Return the minimum value ; Drive Code
function mycmp ( a , b ) { return a [ 0 ] > b [ 0 ] ; } function minSwapsAsc ( arr , n ) { let arrPos = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) arrPos [ i ] = new Array ( 2 ) ; for ( let i = 0 ; i < n ; i ++ ) { arrPos [ i ] [ 0 ] = arr [ i ] ; arrPos [ i ] [ 1 ] = i ; } arrPos . sort ( function ( a , b ) { return a [ 0 ] - b [ 0 ] } ) let vis = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) vis [ i ] = false let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] [ 1 ] == i ) continue ; let cycle_size = 0 ; let j = i ; while ( ! vis [ j ] ) { vis [ j ] = 1 ; j = arrPos [ j ] [ 1 ] ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } function minSwapsDes ( arr , n ) { let arrPos = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) arrPos [ i ] = new Array ( 2 ) ; for ( let i = 0 ; i < n ; i ++ ) { arrPos [ i ] [ 0 ] = arr [ i ] ; arrPos [ i ] [ 1 ] = i ; } arrPos . sort ( function ( a , b ) { return b [ 0 ] - a [ 0 ] } ) let vis = new Array ( n ) ; for ( let i = 0 ; i < n ; i ++ ) vis [ i ] = false let ans = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( vis [ i ] arrPos [ i ] [ 1 ] == i ) continue ; let cycle_size = 0 ; let j = i ; while ( ! vis [ j ] ) { vis [ j ] = 1 ; j = arrPos [ j ] [ 1 ] ; cycle_size ++ ; } if ( cycle_size > 0 ) { ans += ( cycle_size - 1 ) ; } } return ans ; } function minimumSwaps ( arr ) { let S1 = minSwapsAsc ( arr , arr . length ) ; let S2 = minSwapsDes ( arr , arr . length ) ; return Math . min ( S1 , S2 ) ; } let arr = [ 3 , 4 , 2 , 5 , 1 ] ; document . write ( minimumSwaps ( arr ) ) ;