I think I have it, it isn't very clean or optimized but it truly sorts the items together. I will try to optimize later but t took long enough to get working lol. Please give suggestions, and report bugs. Same pastebin link
http://pastebin.com/K0RUL27B. I've only tested it with a small sample but it works with that, and I'm sure it will work with other things too, I'm not sure how well the program will work with a nearly full or full inventory.
EDIT: It doesn't like a full inventory, it also doesn't work very well when there are multiple stacks and the last stack isn't completely full. :/
It works the best when it is half full or less, otherwise there isn't enough spaces to move items around with. There are special cases that work with up to one open slot (all the same item). But for the most part this requires only a half full inventory or less :(/> but still sorting! :D/>
And because turtle.transferTo() returns true even if only part of the stack gets moved it leaves partial stacks behind during the clean up phase, which messes up the sort phase.
EDIT: EDIT: I changed the beginning of the if statement to be a while loop with the same condition in the clean up phase, and, taa-daa, the clean up makes sure that every part of the stack gets moved to the end of the inventory!
EDIT: EDIT: EDIT: I have an idea about how to get the program to work when it is more than half full, but it needs at least one open slot, and it will take a complete rewrite of my sorting phase :(/> I will make a new post once it is done.