Although I could use std::sort() I decided to attempt to sort a string array using bubble sort.
It compiles but I get a seg-fault noted below at a certain point. The exact same algorithm worked fine on an integer array, but it doesnt seem to like the strings,
or is there a more convient sorting method for strings other than cheating with std::sort()?
Code:
#include <iostream>
#include <string>
// function prototype
void sortNames ( std::string[], const int );
// main function - driver /////////////////////////////////////////////////////
//
int main ( void ) {
const int ARRAY_SIZE = 20;
std::string names[ ARRAY_SIZE ] = { "" };
std::cout << "Enter 20 names: ";
for ( int i = 0; i < ARRAY_SIZE; i++ ) {
std::getline ( std::cin, names[ i ] );
}
sortNames ( names, ARRAY_SIZE );
std::cout << "\n\nIn Order:\n\n";
for ( int i = 0; i < ARRAY_SIZE; i++ ) {
std::cout << names[ i ] << std::endl;
}
std::cin.get();
return 0;
}
// function to print the names out alphabetically
void sortNames ( std::string nm[], const int SIZE ) {
for ( int pass = 1; pass < SIZE +1; pass++ ) {
for ( int i = 1; i < SIZE +1; i++ ) {
if ( nm[ i ] > nm[ i + 1 ] ) {
std::string temp = nm[ i ];
nm[ i ] = nm[ i + 1 ]; // SEG FAULTS
nm[ i + 1 ] = temp;
}
}
}
}