I just can't figure out where the bug is, I see nothing wrong with the loops. I'm desperately trying to work this out for about an hour.. Thanks in advance!
have you tested it up to the sort carefully? If not, take them out and verify that output(prim) gives the original expected unsorted list without any crash.