sorting and d_max added