I didn't see a better way of reusing all the shared code parts besides doing what I did.
duplicating the whole thing is ugly as all the setup is the same for partition and sort, the only difference is partition has one extra argument.