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 ; Driver code ; size of step ; array initialized ; length of arr ; calling function
def CheckSort ( arr , k , n ) : NEW_LINE INDENT sortarr = sorted ( arr ) NEW_LINE if ( k == 1 ) : NEW_LINE INDENT print ( " yes " ) NEW_LINE DEDENT else : NEW_LINE INDENT for i in range ( 0 , n ) : NEW_LINE INDENT flag = 0 NEW_LINE for j in range ( i , n , k ) : NEW_LINE INDENT if ( sortarr [ i ] == arr [ j ] ) : NEW_LINE INDENT arr [ i ] , arr [ j ] = arr [ j ] , arr [ i ] NEW_LINE flag = 1 NEW_LINE break NEW_LINE DEDENT if ( j + k >= n ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT if ( flag == 0 ) : NEW_LINE INDENT print ( " Not ▁ possible ▁ to ▁ sort " ) NEW_LINE DEDENT else : NEW_LINE INDENT print ( " Possible ▁ to ▁ sort " ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT k = 3 NEW_LINE arr = [ 1 , 5 , 6 , 9 , 2 , 3 , 5 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE CheckSort ( arr , k , n ) NEW_LINE DEDENT