Question: anagrams are next to each other?
Answer: You can certainly do better as follows: Loop through the array of strings. For each string, first sort its characters, using the sorted string as key and original string as value, put into a hash table. ... iterate over the hash-table and output all anagrams together for a given key, they should be next to each other.