Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array | Function to check if it is possible to sort array or not ; Store the smallest element ; Copy the original array ; Iterate over the given array ; Update smallest element ; Copy elements of arr [ ] to array B [ ] ; Sort original array ; Iterate over the given array ; If the i - th element is not in its sorted place ; Not possible to swap ; Given array ; Function Call
function isPossible ( arr , N ) { let mn = Number . MAX_VALUE ; let B = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { mn = Math . min ( mn , arr [ i ] ) ; B [ i ] = arr [ i ] ; } arr . sort ( ) ; for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != B [ i ] ) { if ( B [ i ] % mn != 0 ) { document . write ( " " ) ; return ; } } } document . write ( " " ) ; return ; } let N = 6 ; let arr = [ 4 , 3 , 6 , 6 , 2 , 9 ] ; isPossible ( arr , N ) ;