# Sort a permutation of first N Natural Numbers by swapping pairs satisfying given conditions

def Swap(x, y, p, posOfCurrNum): posOfCurrNum[p[x]], posOfCurrNum[p[y]] = posOfCurrNum[p[y]], posOfCurrNum[p[x]] p[x], p[y] = p[y], p[x] return p, posOfCurrNumdef sortArray(p, n): posOfCurrNum = [0] * (n + 1) for i in range(1, n + 1): posOfCurrNum[p[i]] = i ans = [] for i in range(1, n + 1): if (p[i] == i): continue j = posOfCurrNum[i] if (abs(i – j) * 2 >= n): p, posOfCurrNum = Swap(i, j, p, posOfCurrNum) ans.append([i, j]) elif (n // 2 = n // 2): p, posOfCurrNum = Swap(i, n, p, posOfCurrNum) ans.append([i, n]) p, posOfCurrNum = Swap(j, n, p, posOfCurrNum) ans.append([j, n]) p, posOfCurrNum = Swap(i, n, p, posOfCurrNum) ans.append([i, n]) else: p, posOfCurrNum = Swap(i, n, p, posOfCurrNum) ans.append([i, n]) p, posOfCurrNum = Swap(n, 1, p, posOfCurrNum) ans.append([n, 1]) p, posOfCurrNum = Swap(1, j, p, posOfCurrNum) ans.append([1, j]) p, posOfCurrNum = Swap(1, n, p, posOfCurrNum) ans.append([1, n]) p, posOfCurrNum = Swap(i, n, p, posOfCurrNum) ans.append([i, n]) print(len(ans)) for p in ans: print(p[0], p[1])if __name__ == ‘__main__’: n = 6 p = [ 0, 2, 5, 3, 1, 4, 6 ] sortArray(p, n)