I am not exactly sure what is required, but maybe this would help get started.
In J1 put
Then extend this formula to Q1. Then extend J1:Q1 downward as far as needed.
(The title of the post mentions sorting, but the requirement seems not to involve any sorting.)