Sort an array of strings
Bobb Fwed
Posts: 1,119
So I wonder if someone has done this before. Or if not, what are some pointers to do this?
The string addresses are stored in an array, and the best option would be to arrange the original array (not creating a new one -- so not to increase memory usage).
Any help would be nice.
The string addresses are stored in an array, and the best option would be to arrange the original array (not creating a new one -- so not to increase memory usage).
Any help would be nice.
Comments
What you will be sorting is the array of string addresses using the strings themselves for comparison. You'll need to be able to compare two strings for "less than" given their addresses.
Attached is my test code. I will implement it in the next version of Memory Storage Management. I might try a couple different sorting methods, as there may be quite a few strings to sort, thus speed will become an issue. Insertion sort doesn't seem too complicated, and it should be faster in pretty much all situations.
It takes up a lot less code space than cocktail sorting, and it's faster.
I just finished it, and it seems to work, I will test it more.
Now I need to make it so it isn't case sensitive (or optionally not).
Download here: http://obex.parallax.com/objects/715/
I have included bubble sort, cocktail sort, insertion sort, shell sort, and quick sort. The first two are pretty worthless (under almost all circumstances) once you introduce the last three.
There is a lot to learn in the objects...
Massimo
Changes:
1) Most importantly, I have been able to find optimizations for all five sorting algorithms. Most significantly, quick sort. For decimal sorting, it is almost always the fastest sorting method as long as there are more than 17 elements in the array. Less than 17, it is only slightly slower than insertion sort.
2) Now all methods have the order (ascending/descending) option. I did not have these on shell and quick sort before.
3) In the string demo, the strings are now randomly arranged before sorting (for less bias times). There are also (optionally) 90 strings to arrange in the demo.
Here is a chart to help determine which is best for your uses (it is based on the speed of the demo):
Alternatively the shell sort would only use 13 longs of stack, no matter the size of the array.