Question: how did the sword of gryffindor get in the sorting hat?
Answer: In May of 1993, the sword materialised inside the old school Sorting Hat and appeared to Harry Potter, whom the hat was given to when he arrived in the Chamber of Secrets to save his best friend's sister, Ginny Weasley, from being drained of her life force by Tom Riddle's Diary and eaten by the Basilisk.