Every sent mail contains a header Message-Id, with value uniquiely and globally identifying the message. When a reply to such message is sent, it contains a header field In-Reply-To: having as value the Message-Id of the original mail. Of course, the replying mail has its own unique Message-Id.
Replying to mails, having already In-Reply-To, preserves the mail headers, but adds one more In-Reply-To:, indicating that the reply is not only sent to the very initial mail, but also to the mail currently being replied.
Mails composed in this way contain the definite information of the order the messages were sent, and can be undoubtfully hierarchically sorted, based on which mail is answer of which mail. Correct implemented mail clients use this information. Incorrect implemented mail clients build the mail threads based on the time of the answer and similar subjects.