Find if array can be sorted by swaps limited to multiples of k | CheckSort function To check if array can be sorted ; sortarr is sorted array of arr ; If k = 1 then ( always possible to sort ) swapping can easily give sorted array ; Comparing sortarray with array ; Element at index j must be in j = i + l * k form where i = 0 , 1 , 2 , 3. . . where l = 0 , 1 , 2 , 3 , . . n - 1 ; If element is present then swapped ; If element of sorted array does not found in its sequence then flag remain zero that means arr can not be sort after swapping ; If flag is 0 Not possible else Possible ; Size of step ; Array initialized ; Length of arr ; Calling function
function CheckSort ( arr , k , n ) { var sortarr = arr . sort ( ( a , b ) => a - b ) ; if ( k === 1 ) document . write ( " " ) ; else { var flag = 0 ; for ( var i = 0 ; i < n ; i ++ ) { flag = 0 ; for ( var j = i ; j < n ; j += k ) { if ( sortarr [ i ] === arr [ j ] ) { var tmp = arr [ i ] ; arr [ i ] = arr [ j ] ; arr [ j ] = tmp ; flag = 1 ; break ; } if ( j + k >= n ) { break ; } } if ( flag === 0 ) { break ; } } if ( flag === 0 ) document . write ( " " ) ; else document . write ( " " ) ; } } var k = 3 ; var arr = [ 1 , 5 , 6 , 9 , 2 , 3 , 5 , 9 ] ; var n = arr . length ; CheckSort ( arr , k , n ) ;