Re: Quicksort for list of string
<aparnakakkar2003@gmail.com> wrote in message
news:1176983446.882491.29820@p77g2000hsh.googlegroups.com...
can any one tell me if I give the followiing string in input:
ABC
abc
BBC
then how I can get
ABC
abc
BBC
or
abc
ABC
BBC
as my output usiing quicksort.
Well, this doesn't use quicksort but std::sort which is O( N log N ).
Output is:
Before sort:
ABC
abc
BBC
ABCD
aB
After sort:
ABC
ABCD
BBC
aB
abc
After Case Insensitive sort:
aB
ABC
abc
ABCD
BBC
There may be a better/faster algorithm for the case insensitve comparing of
std::strings. I just did this one rather quickly.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
bool CILessthan( const std::string Elem1, const std::string Elem2 )
{
for ( std::size_t i = 0; i < Elem1.length(); ++i )
{
if ( std::tolower( Elem1[i] ) < std::tolower( Elem2[i] ) )
return true;
else if ( std::tolower( Elem1[i] ) > std::tolower( Elem2[i] ) )
return false;
}
// Equal up to this point, but one may be longer
if ( Elem1.length() < Elem2.length() )
return true;
return false;
}
void ShowData( const std::vector<std::string>& Data )
{
for ( std::vector<std::string>::const_iterator it = Data.begin(); it !=
Data.end(); ++it )
std::cout << (*it) << "\n";
}
int main()
{
std::vector<std::string> Data;
Data.push_back( "ABC" );
Data.push_back( "abc" );
Data.push_back( "BBC" );
Data.push_back( "ABCD" );
Data.push_back( "aB" );
std::cout << "Before sort:\n";
ShowData( Data );
std::sort( Data.begin(), Data.end() );
std::cout << "\nAfter sort:\n";
ShowData( Data );
std::sort( Data.begin(), Data.end(), CILessthan );
std::cout << "\nAfter Case Insensitive sort:\n";
ShowData( Data );
std::string wait;
std::getline( std::cin, wait );
}