First, do you know how to code a sort? You could read your textbook or look here
Once you can sort one array, simply modify the function to take both the names and numbers arrays. Sort based on names - every time you move two names about, make the same exchange between same indexes in the numbers array.
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
To sort strings instead of numeric values, use the strcmp( ) function instead of < or >.
When you do the exchanges, do them for both the names and the ph. numbers arrays.
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
Yes, you've got it.
A couple comments.
for(i = 1; (i <= arrayLength) && flag; i++)
{
flag = 0;
for (j=0; j < (arrayLength -1); j++)
{
Bubble sort can be made a bit better by not checking all the way to the end every time through the outer loop. You've put the item at the end that belongs there, so don't visit it again. Also, loops dealing with arrays generally are written with counter at 0, go to < size. Just an idiom you should be consistent with. And, in Bubble (and some other simple sorts), the main loop should go one less time than there are items. After the last two are sorted, there's nothing gained by looking at just one item.
So, try this (not that you'll be able to measure a difference on any small data sets)
for(i = 0; (i < arrayLength-1) && flag; i++)
{
flag = 0;
for (j=0; j < (arrayLength -1 - i ); j++)
{
I'm glad to see you used the flag to stop short when a full pass is made with no swaps. You don't need to set the flag to 1 twice in the swap block.
Is this int arrayLength = array.length( ); really working for you? You get the length of your arrays (the number of valid items) from the counters n or i in your reading loops. Matter of fact, you should check that n and i are the same, to ensure good data has been read in.
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
More likely he's using a vector to store the bunch of strings as opposed to your creating the 2D char array. Like I said before, n or i give you that information.
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228
so i can get rid of the = array.length( )
absolutely
vmanes
Posting Virtuoso
1,914 posts since Aug 2007
Reputation Points: 1,268
Solved Threads: 228