I think this post/function from @Erik Mahieu may interest you:
Pixel sorting according to different methods