Thursday, July 9, 2009

How do I sort an array of strings in C++?

I really can't figure this out! If I could have an example of a sorting algorithm that would work on an array of names, I would really appreciate it.


-No bubble sort


-Only use iostream.h and strings.h if necessary


-Thanks!

How do I sort an array of strings in C++?
Here is an algorithm called selection sort.





#include %26lt;iostream%26gt;


# include %26lt;string%26gt;





void selectionSort(string array[ ], const int arraySize);


int findSmallest(string array[ ], int startIndex, int endIndex);


void swap(string%26amp; first, string%26amp; second);


void print(string array[ ], const int arraySize);





int main( )


{


const int ARRAY_SIZE = 3;


string someArray[ARRAY_SIZE] = {"cat", "mouse", "dog"};


selectionSort(someArray, ARRAY_SIZE);


print(someArray, ARRAY_SIZE);





return 0;


}





void selectionSort(string array[ ], const int arraySize)


{


int smallestIndex = 0;


for(int i = 0; i %26lt; arraySize; i++)


{


smallestIndex = findSmallest(array, i, arraySize - 1);


swap(array[i], array[smallestIndex]);


}


}





int findSmallest(string array[ ], int startIndex, int endIndex)


{


int smallestIndex = startIndex;





for(int i = startIndex + 1; i %26lt;= endIndex; i++)


{


if(array[i] %26lt; array[smallestIndex])


smallestIndex = i;


}


return smallestIndex;


}





void swap(string%26amp; first, string%26amp; second)


{


string temp = first;


first = second;


second = temp;


}





void print(string array[ ], const int arraySize)


{


for(int i = 0; i %26lt; arraySize; i++)


cout %26lt;%26lt; array[i] %26lt;%26lt; endl;


}
Reply:There are plenty of different sorts out there, and they can all be applied to arrays/variables/objects of any kind. You just have to write the comparison function yourself





Lookup these sorts on the net:


Insertion Sort


Shell Sort


Quicksort


radix sort


mergesort





There is alot of example code out on the internet. These are very common programming tasks





Note: Insertion sort is probably the easiest to program(but not the most efficient)


No comments:

Post a Comment