Song Lyrics | Credit Card Consolidation | Loans | Internet Advertising | MPAA
passing arrays in c++... [Archive] - PCMech Forums

PDA

View Full Version : passing arrays in c++...


GSXdan
09-11-2003, 12:58 PM
i cant find any good algoritms to sort and array of strings in alphabetical order. anyone know of a good one that is used for this purpose or at least close, so i can modify it?

thanks

aym
09-14-2003, 08:28 AM
sorting strings is similar to sorting numbers, the only difference is comparing two strings, while you can use the < or > operators with numbers, you can't do so with C strings, some of the options you have:
using <string.h> comparison functions like strcmp and stricmp, check out cppreference.com or msdn for more info about these functions.
Another option is using the string class that comes with C++ STL (Standard Template Library), again check out cppreference for more info.
As for the sorting algorithm itself, there a lot of algorithms, if you want something simple, use bubble sort, it works fine for small arrays (like 20) if you have larger arrays, you may consider using heap sort or quick sort, I recommend heap sort because it's easier to understand and implement for a new comer to sorting.
Just Google for the sort algorithm name and you'll find info about it, read it, and if you can't understand anything, just post :)

EDIT:

strcmp:
http://cppreference.com/stdstring_details.html#strcmp

c++ string:
http://cppreference.com/cppstring.html

Bubble sort:
http://linux.wku.edu/~lamonml/algor/sort/bubble.html

Heap sort:
There used to be a great site for heap sort, but I can't manage to find it right now :(

GSXdan
09-14-2003, 10:01 AM
yea i found a modified bubble sort that i came up w/ last year that words just fine for this:


void Sort(char words[][20], int numwords) {



int last, next, test;
char temp[20];

for(int i=1;i<numwords;i++)
{
last=numwords-i;
for(int j=0;j<last;j++)
{
next=j+1;
test=strcmp(words[j], words[next]);
if(test>0)
{
temp=words[j];
words[j]=words[next];
words[next]=temp;

}
}
}


return;


}

thanks again ^dan

GSXdan
09-14-2003, 10:04 AM
the code isnt showing up correctly for some reason??? if you want to see it i can post the cpp file.

^dan