About 2nd method

mam by you 2nd method we get ans in less time.But what about sorting the algorithm that we used for have time conplaxity order of n^2. Then how will it be efficient ?What kind of algorithm should we use for sorting here?