Глава 01 (продолжение 1)
//применение параметризованной быстрой сортировки к пользовательским
//классам
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
const int NUM_ITEMS = 4;
class address{
char name[40];
char street[40];
char sity[20];
char state[3];
char zip[11];
public:
address(char *n,char *s,char *c,char *st,char *z);
address(){};
int operator<(address &ob)
{
return strcmp(zip,ob.zip)<0;
}
friend ostream &operator<<(ostream &stream,address &ob);
};
//Address constructor
address::address(char *n,char *s,char *c,char *st,char *z)
{
strcpy(name,n);
strcpy(street,s);
strcpy(sity,s);
strcpy(state,st);
strcpy(zip,z);
}
//Inserter for address class
ostream &operator<<(ostream &stream,address &ob)
{
cout<<ob.name<<endl;
cout<<ob.street<<endl;
cout<<ob.sity<<" "<< ob.state<<" ";
cout<<ob.zip<<endl<<endl;
return stream;
}
address addrs[NUM_ITEMS] = {
address ("A.Alexander","101 1st St","Olney","Ga","55555"),
address ("B.Bertrand","22 12nd Ave","Oaklend","Pa","34232"),
address ("C.Carlisle","33 3rd Blvd","Ava","Or","92000"),
address ("D.Dodger","4 4rth Dr","Fresno","Mi","45678"),
};
template <class Stype> void quick(Stype *item,int count);
template <class Stype> void qs(Stype *item,int left,int right);
main()
{
int i;
cout<<"Unsorted Addresses : \n\n";
for(i=0;i<NUM_ITEMS;i++)cout<<addrs[i];
quick(addrs,NUM_ITEMS);
cout<<"Addresses sorted by ZIO code :\n\n";
for(i=0;i<NUM_ITEMS;i++)cout<<addrs[i];
return 0;
}
//Входная функция быстрой сортировки
template <class Stype> void quick(Stype *item,int count)
{
qs(item,0,count-1);
}
template <class Stype> void qs(Stype *item,int left,int right)
{
register int i,j;
Stype x,y;
i=left;j=right;
x=item[(left+right)/2];
do {
while(item[i]<x && i<right) i++;
while( x<item[j] && j<left) j--;
if(i<=j) {
y=item[i];
item[i]=item[j];
item[j]=y;
i++;j--;
}
}
while(i<=j);
if(left<j) qs(item,left,j);
if(i<right) qs(item,i,right);
}
Результат:
C.Carlisle
33 3rd Blvd
33 3rd Blvd Or 92000
D.Dodger
4 4rth Dr
4 4rth Dr Mi 45678
Addresses sorted by ZIO code :
C.Carlisle
33 3rd Blvd
33 3rd Blvd Or 92000
D.Dodger
4 4rth Dr
4 4rth Dr Mi 45678
A.Alexander
101 1st St
101 1st St Ga 55555
B.Bertrand
22 12nd Ave
22 12nd Ave Pa 34232
Назад |
Начало урока |
Вверх |
Вперед
Содержание