Sunday, August 2, 2009

Using C++ How can I alter the code so it will print the array of names in alphabetical order?

Below --%26gt; Program, Actual Output, and Desired Output:





Program:


int main


{


string names[3] = {"Smith, John", "Anthony, Mark", "Gibson, Mel"};





bubble_sort(names[3]);





for(index=0; index%26lt;3; index++)


cout%26lt;%26lt;names[index]%26lt;%26lt;"\n";


}





void bubble_sort(string%26amp; array)


{


int i, j, flag = 1;


char temp;


int arrayLength = array.length( );


for(i = 1; (i %26lt;= arrayLength) %26amp;%26amp; flag; i++)


{


flag = 0;


for (j=0; j %26lt; (arrayLength -1); j++)


{


if (array[j+1] %26gt; array[j])


{


temp = array[j];


array[j] = array[j+1];


array[j+1] = temp;


flag = 1;


}


}


}


return;


}





Actual OUTPUT:


Smith, John


Anthony, Mark


Gibson, Mel








Desired OUTPUT:


Anthony, Mark


Gibson, Mel


Smith, John

Using C++ How can I alter the code so it will print the array of names in alphabetical order?
Several problems:





%26gt; bubble_sort(names[3]);





this is accessing the 4th element of the names array (first 3 elements are at indices 0, 1, and 2). this is why you're getting your output, it's not sorting anything! i'm surprised this program didn't crash. instead you simply want to pass 'names' as the parameter - this means you are passing the entire array as a parameter, not a single element of the array. proper:


bubble_sort(names);





%26gt; if (array[j+1] %26gt; array[j])





this would sort the array opposite the way you want it. simple fix is using less-than instead of greater-than. BUT, if i'm not mistaken, you can't compare strings like that. you have to use strcmp, like this:


if (strcmp(array[j+1], array[j]) %26lt; 0)


otherwise, you are just comparing pointers.

statice

No comments:

Post a Comment