Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array | C ++ implementation of the above approach ; 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 ; Driver Code ; Given array ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; void isPossible ( int arr [ ] , int N ) { int mn = INT_MAX ; int B [ N ] ; for ( int i = 0 ; i < N ; i ++ ) { mn = min ( mn , arr [ i ] ) ; B [ i ] = arr [ i ] ; } sort ( arr , arr + N ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] != B [ i ] ) { if ( B [ i ] % mn != 0 ) { cout << " No " ; return ; } } } cout << " Yes " ; return ; } int main ( ) { int N = 6 ; int arr [ ] = { 4 , 3 , 6 , 6 , 2 , 9 } ; isPossible ( arr , N ) ; return 0 ; }