Implemented solution using Sort and loops