воскресенье, 10 октября 2010
Задание - алфавитная сортировка строки (модулярный вид, с Class String). Ну, сделала через тупую сортировку, но execution time - убийственен. Думаю надо задействовать strtok и пузырьковый метод. Но что-то сооовсем не получается. Ниже имеющийся рабочий код. Помогите, пожалуйста, с void sort () в первом more. Как исправить на другой метод(какой)? Я не кодер ни разу, только непосредственно с железом работаю.-___-
рабочий код с неправильной сортировкой
#include "str.h"
#include
#include
#include
using namespace std;
void sort ( String *a, int n )
{
int changed;
String temp;
do {
changed = 0;
for ( int i = 0; i < n - 1; i++ ) {
if ( a[i+1] < a[i] ) {
temp = a[i];
a[i] = a[i+1];
a[i+1] = temp;
changed = 1;
}
}
} while ( changed );
}
void input ( String *a, int limit, int &i )
//value of i will be passed out as size
{
static char buffer[100];
cout << "\nenter data:";
for ( i = 0; i < limit; i++ )
if ( scanf( "%s", buffer ) == EOF )
break;
else
a[i] = String ( buffer );
}
void output( String *a, int size )
{
cout << "\nlist : ";
for ( int i = 0; i < size; i++ )
a[i].prints();
//cout << a[i];
cout << endl;
}
int main()
{
const int max = 10;
String list[max];
int size = 0;
String x, y;
input ( list, max, size );
sort ( list, size );
output ( list, size );
return 0;
}
str.h
#ifndef STR_H
#define STR_H
#include
using namespace std;
class String {
protected:
char *str;
public:
//constructors
String(); //create an empty string
String ( char *init ); //initializes str to string init
int length(); //returns length of this string
void prints(); //prints this string
bool operator < ( String &s ); //if this String < String s returns true
//else false
int find_pat( String pattern );//returns an index i such that pattern
//matches the substring of this string that
//begins at position i, returns -1 if no match
void operator << ( ostream &out );
};
#endif
str.cpp
//str.cpp
#include
#include
#include "str.h"
String::String()
{
str = new char[1]; //points to new node
*str = 0; //initializes to NULL string
}
String::String( char *s )
{
str = new char[ strlen( s ) + 1 ];
strcpy( str, s );
}
int String::length()
{
return( strlen( str ) );
}
void String::prints()
{
cout << str << "\n";
}
bool String::operator < ( String &s )
{
return ( strcmp( str, s.str ) < 0 );
}
//ostream & String::operator << ( ostream &out )
void String::operator << ( ostream &out )
{
out << str << endl;
//return out;
}
@темы:
C++,
Алгоритм