Need Help with array sort


this is assignment from my school that I try to figure out. It read from .txt file and store it in an array name codes [ ] for the zipcode and ship [ ] for the shipping charges.

so my logic will be :

1. only zip code need to be compared.

rules :

when read file from the .txt file the zip must be stored as arrays of string called ship [ ].

questions :

- Please tell me if there any bad habit in my coding
- How to compare those two zipcodes and sort it???




void ZipShip::sort()
{
int j,i,min;
string tempZip;
double tempShip;
for(i=0;i<numEntries-1;i++);
{
min=i;
for(j=i+1;j<numEntries;j++)
{
if(codes[j]<codes[i])
{
min=j;

}

}
if ( min != i ) {
swap(codes[i], codes[min]);
swap(ship[i],ship[min]);}
}

}
It is better to define variables i, j as local variables of the loops. Also it is not clear why variables tempZip and tempShip were declared when they are not used in the code of the function. Moreover after the control statement of the first loop you placed a semicolon. It is obviously a bug.

Taking into account all what was said the code could look the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void ZipShip::sort()
{
   for ( int i = 0; i < numEntries-1; i++ )
   {
      int min = i;

      for ( int j = i+1; j < numEntries; j++ )
      {
         if ( codes[j] <codes [min] ) min = j;
      }

      if ( min != i ) 
      {
         swap( codes[i], codes[min] );
         swap( ship[i], ship[min] );
      }
   }
}
i'm sorry,

the first pseudo is kinda of like:

tempZip=codes[min];

codes[min]=code[j];

codes[j]=tempZip;

and yes vlad thank you about the semi colon, i try to delete that..but it did not work out. Is there something wrong with my code??

or is it because string cannot be compared like that?
class std::string has the copy assignment operator. So you may assign one object of type std::string to other object of the same type.
If you do not use standard function std::swap then the code I showed above could look the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void ZipShip::sort()
{
   for ( int i = 0; i < numEntries-1; i++ )
   {
      int min = i;

      for ( int j = i+1; j < numEntries; j++ )
      {
         if ( codes[j] <codes [min] ) min = j;
      }

      if ( min != i ) 
      {
         std::string tempZip = codes[min];
         codes[min] = codes[i];
         codes[i] = tempZip;

         double tempShip = ship[min];
         ship[min] = ship[i];
         ship[i] = tempShip;
      }
   }
}
Last edited on
Topic archived. No new replies allowed.