Category: Natural Numbers

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, […]

Continue Reading