UNB/ CS/ David Bremner/ teaching/ cs3383/ lectures/ 13.1-demos/ partition.py
#!/usr/bin/env python3
def partition(A,p,q,loc):
    A[p],A[loc] = A[loc],A[p]
    i = p
    for j in range(p+1,q+1):
        if A[j] <= A[p]:
            i += 1
            A[i], A[j] = A[j], A[i]
    A[i], A[p] = A[p], A[i]
    return i

if __name__ == "__main__":
    from random import sample,randrange
    from partition import partition

    A = sample(range(20),20)
    print("A=",A);

    loc = randrange(0,20)
    pivot = A[loc]
    print("loc={:d} pivot={:d}".format(loc,pivot))

    k = partition(A,0,19,loc)

    print("k=",k)
    print("A=",A)