Check if it is possible to sort an array with conditional swapping of elements at distance K | Function for finding if it possible to obtain sorted array or not ; Iterate over all elements until K ; Store elements as multiples of K ; Sort the elements ; Put elements in their required position ; Check if the array becomes sorted or not ; Driver code
function fun ( arr , n , k ) { let v = [ ] ; for ( let i = 0 ; i < k ; i ++ ) { for ( let j = i ; j < n ; j += k ) { v . push ( arr [ j ] ) ; } v . sort ( ) ; let x = 0 ; for ( let j = i ; j < n ; j += k ) { arr [ j ] = v [ x ] ; x ++ ; } v = [ ] ; } for ( let i = 0 ; i < n - 1 ; i ++ ) { if ( arr [ i ] > arr [ i + 1 ] ) return false ; } return true ; } let arr = [ 4 , 2 , 3 , 7 , 6 ] ; let K = 2 ; let n = arr . length ; if ( fun ( arr , n , K ) ) document . write ( " " ) ; else document . write ( " " ) ;