Sort:  

I tried my best to keep it as simple as possible, hope you got the basic outline of the problem :)