1. I think your sorting code may not works well. (but can't find counter example. what the...)
for(j=0; j<len; j++) --> for(j=0; j<i; j++)
change j-for state like this.
2. last line sentence will endup by EOF. so it will have some problem with your code.
You are sorting 0-to-(len-2) strings. but last line sentence's len-1 character is NOT '\n'. So if input is like "abz", you will return "baz"