Could you write a paragraph-sized comment describing everything that's happening in `apply_sorting`? It currently takes a bit too much concentration to understand all the things this does.