improved the first group sorting algorithm

but don't look at the code, its ugly as hell!