views:

235

answers:

2

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:

  1. lastFirstLetter := Copy(CurrentItem, 1, 1)
  2. go to next item
  3. currentFirstLetter := Copy(CurrentItem, 1, 1)
  4. 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.

+1  A: 

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'

Thank you very much! Probably every programmer does know this website but I didn't :D The site is great!
+3  A: 

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.

lkessler
Thank you, helpful information!