If sort_inventory is set, items will be inserted into your inventory in order by type than alphabetical. This, all scrolls will be grouped together, but in alphabetical order. Same for all weapons. This only applies to new items you pick up - items that you are already holding will not be sorted.

If sort_inventory is not set (default), items will be inserted via type, subtype and magic. This, all axes will be grouped together in magic order, all daggers by magic order, etc. Unfortunately, for scrolls and rings, new ones just get inserted last.

If you have a lot of stuff that is not in alphabetical order but you would like it to be, the best method is to drop all of it and then pick it up.
