Sort a string list: Move or exchange items only
In Delphi / Pascal I would like to sort a TStringList alphabetically. But for this purpose, I can only use the following two methods:
Move: Moves a string from one index position to another, shifting other strings around as appropriate.
Exchange: Swaps two strings in the list, as开发者_开发技巧 identified by their index positions.
How could I do this? I had the idea to go through all items with a loop and to something like this:
- lastFirstLetter := Copy(CurrentItem, 1, 1)
- go to next item
- currentFirstLetter := Copy(CurrentItem, 1, 1)
- if ord(currentFirstLetter) < ord(lastFirstLetter) then exchange(lastItem, currentItem)
What would be the fastest way to sort a StringList with these two methods? I can't use the sort method and the sorted property by the way.
You give two methods: (1) Swap and (2) Exchange.
There is a third method:
(3) Keep a TList of pointers to your strings and sort the pointers.
This method will leave all your strings where they are and could be faster.
See the question: Best Way To Sort An Array In Delphi and Barry Kelly's accepted answer as well as the other answers.
move / exchange methods are all you need. However you've got a lot of algorithms to choose from! Have a look at this site (from a quick Google search) for animated comparisons: http://www.sorting-algorithms.com/
I think that all these algorithms just use 'move', apart from heap and the quicksorts which only use 'exchange'
精彩评论