the program i have to make is as follows:

use the string comparison function and the sorting array techniques to write a program that alphabetizes a list of strings. use 10 town names for your program.


and this si what i have made.... and it doesnt work:

#include<iostream>
 using namespace std;
 #include<iostream>
 using namespace std;
 #include<cstring>
 using std::strncmp;
 
 int main()
 {
 const int ArraySize = 10;
 const char *Array[] = { "Toronto", "Montreal", "Alberta", "Quebec", "NewYork", "Calgary", "Edmonton", "NewJersey", "Ontario", "California" };

  cout << "The unsorted arangement of the town names is: \n"<<endl;
 for ( int i = 0; i < ArraySize; i++ )
 {
 cout <<" " << Array[i];
 cout << endl << "\n";
 }
 
 cout << "The sorted arangement of the town names is: \n"<<endl;
 for ( int next = 0; next < ArraySize; next++ )
 {
 if ( strncmp(Array[next],Array[next-1],3) == -1)
 {
 Array[next] = Array[next];
 }
 if( strncmp(Array[next],Array[next-1],3) == 1)
 {
 Array[next] = Array[next - 1];
 }
 
 }
 
 for ( int j = 0; j < ArraySize; j++ )
 {
 cout <<" " << Array[j];
 cout << endl << "\n";
 }
 
 

  return 0;
 
 }

any ideas on what is wrong? and what solution is there??

thank you

Please use code tags. Find more information about them here:

Your sorting algorithm is fundamently flawed:

for ( int next = 0; next < ArraySize; next++ )
{
  if ( strncmp(Array[next],Array[next-1],3) == -1)

I don't quite understand what you're doing here. In the first iteration of the loop, next will be equal to 0, so the second parameter you'll be passing to strncmp() will be... Array[-1]. That won't work. I think that you might want next to be initialized at 1.

{
Array[next] = Array[next];

Um, ok, so then why bother putting this line in at all?

}
if( strncmp(Array[next],Array[next-1],3) == 1)
{
Array[next] = Array[next - 1];
}

And if you're going to swap variables, you are going to need to have an "in-between" variable to hold the value of 1 while the other is being swapped. You're just loosing the value contained in Array[next] with that statement right there.

And even fixing that, it still will not work, as you aren't implementing the Bubble sort algorithm correctly (which is what it seems you're trying to do). This is what the Bubble sort does:

  • Compares the first 2 values. If the second is smaller than the first, it swaps them.
  • Keeps comparing and swapping through the whole list.
  • Starts over, doing the whole process again.
  • Depending on how large your list is, you may have to do this many times to get the entire list sorted.

If this seems redundant, it is. The bubble sort is one of the slowest sorting algorithms, although you probably don't need to worry about speed right now, as the list is relatively small.

Hope this helps

Edited 3 Years Ago by mike_2000_17: Fixed formatting

As a noob myself, I play with these examples as a learning experience, and if i can, help others .

I changed the the inital value of next to 1 a reccomended, AND switched the order of the arrays in the strncomp(). The first "if " is a "do nothing and probably can be deleted?

Anyway, the biggest revelation was when I ran it through the debugger to find that NIETHER condition for swap was ever returned by strncomp()!

Now THAT seems strange!

I added some cout's to see what variable was doing what, but never got any output!

Could we have some Guru input on this, please?

cout << "The sorted arangement of the town names is: \n"<<endl;
for ( int next = 1; next < ArraySize; next++ )
{
if ( strncmp(Array[(next-1)],Array[next],3) == -1)
{
Array[next] = Array[next];
}
if( strncmp(Array[next-1],Array[next],3) == 1)
{
    cout << "initially next-1 is: " << Array[next-1] <<endl;
  const  char* temp[ArraySize];
 temp[next] = Array[next];

Array[next-1] = temp [next];
cout << "now it's: " << Array[next-1]<< endl;
}

Just had a EURIKA moment after looking up the the spec for strncmp(). It says that it will return an integer >,<, or =0, depending on the string relationship.
It DOES NOT say WHAT that integer is!
Changing the the boolean relationship to >0 rather than == 1 made the function come to life!

It's amazing what one can learn from just screwing around!

but still that program does not alphabetize the names!

all it does is compares two consequtive names.

but still that program does not alphabetize the names!

all it does is compares two consequtive names.

Hints:

1. Use a nested for loop. I.e a for loop within itself
2. Find out what strcmp returns.
3. How do you swap elements of the array. Do you need to create a temporary variable?

All VERY good hints! I had it alphabetizing soon after I got strncmp() working. You have to fix BOTH "if" statements and their attendant functions. Also think about what the "next" loop is actually doing.
There is a simple statement to make it "do more".

To my surprise, two "if" statements were needed. Each checking a different "direction". Once you get it to work, try commenting one set out and see what happens. I thought it was educational..

If I tell you the answer, then you will NEVER get a feel for this stuff! Learn by deductive reasoning-it's the only way.

All VERY good hints!

Thank you. And no you only need one if statement, if you are using a nested for loop like I suggested.

thankx alot guys

got it to work

used two for loops and one if statement

works fine

thx alot

thankx alot guys

got it to work

used two for loops and one if statement

works fine

thx alot

Can you post your code for the benefit of the rest of the community.

AHA! Now it works more like I expected it to in the first place!
I'll let the OP post his solution before i do mine.
Rather than a nested loop, I used a "recursive" solution on the loop by resetting the "next" variable. My error was in resetting to 1, only to have the loop bump the position to 2, so next-1 skipped over the 0
position. resetting to 0 got the loop to start CORRECTLY.

I learned alot from this! THANKS

i made a bubblesort function

void BubbleSort( const char *array[] , int size )
{
 
    int result;
 
 for ( int next = 0; next < size - 1 ; ++next )
 {
  for ( int j = 0; j < size - 1 - next; ++j )
  {
                result = strcmp (array[j], array[j+1]);
 
                if (result > 0)
     swap ( array[j] , array[j+1] );
  }   
 }
}

and in the main i just did the cout...

i made a bubblesort function

void BubbleSort( const char *array[] , int size )
{
 
    int result;
 
 for ( int next = 0; next < size - 1 ; ++next )
 {
  for ( int j = 0; j < size - 1 - next; ++j )
  {
                result = strcmp (array[j], array[j+1]);
 
                if (result > 0)
     swap ( array[j] , array[j+1] );
  }   
 }
}

and in the main i just did the cout...

Man! That doesn't look ANYThing like your ORIGINAL work, which was basically OK!
Below is my solutiion using your work.
The commented out part is how to fix YOUR original method.
The current solution uses that handy swap funtion that appeared out of thin air.

Both will work. To toggle the solutions, just uncomment the code, but be sure to comment out the swap functon.

for ( int next = 1; next < ArraySize; next++ )
{

if( (strncmp(Array[next-1],Array[next],3) ) > 0)
{

    //const char* temp[ArraySize];
    //temp[next-1] = Array[next-1];
    //Array[next-1] = Array[next];
    //Array[next] =temp[next-1];
    swap(Array[next],Array[next-1]);

    next=0;
}

You had it all along! You just needed a few tweeks!!!!

Man! That doesn't look ANYThing like your ORIGINAL work, which was basically OK!
Below is my solutiion using your work.
The commented out part is how to fix YOUR original method.
The current solution uses that handy swap funtion that appeared out of thin air.

Both will work. To toggle the solutions, just uncomment the code, but be sure to comment out the swap functon.

for ( int next = 1; next < ArraySize; next++ )
{

if( (strncmp(Array[next-1],Array[next],3) ) > 0)
{

    //const char* temp[ArraySize];
    //temp[next-1] = Array[next-1];
    //Array[next-1] = Array[next];
    //Array[next] =temp[next-1];
    swap(Array[next],Array[next-1]);

    next=0;
}

You had it all along! You just needed a few tweeks!!!!

I highly doubt you can do this without a nested for loop. Prove me wrong.

JRM your solution won't work, bubble sort uses two nested loops not one.

And on top of that you cripple your method by using strncmp( ) instead of just strcmp( ). Why limit the comparision to 3 characters ?

I highly doubt you can do this without a nested for loop. Prove me wrong.

I tested both versions before i posted!
His original code is in this thread.
cut 'n paste 'n compile 'n run!
Simple, compact and a thing of beauty (if I must say so myself-LOL)

Unfortunatly, I'm not smart enough to be able to cut and paste the output terminal in codeblocks!!

I tested both versions before i posted!
His original code is in this thread.
cut 'n paste 'n compile 'n run!
Simple, compact and a thing of beauty (if I must say so myself-LOL)

Unfortunatly, I'm not smart enough to be able to cut and paste the output terminal in codeblocks!!

He he, showing your output doesn't prove much. No offence but you're prolly wrong, if not you're a genius :p

But if you right - click on the top bar of the console window you can choose select all and copy, for future reference. Not sure how it works in code blocks?

As far as why the limits? I don't know! I'm NOT the OP!
I'm just tinkering with the original to make it work as he specified.
As for my code, ther ARE two loops...sort of (no pun intended).
The reset makes it recursive , so it keeps going until there is nothing else to do! Try it..

Now you've said recursive I'm not so sure. :lol:

You need to provide a better example of your code then with all relevant parts shown and not commented out.

Are you saying that the swap( ) function in your code is recursive ?

Because the only function I see in that post is the bubble sort and swap( ) .

i made a bubblesort function

void BubbleSort( const char *array[] , int size )
{
 
    int result;
 
 for ( int next = 0; next < size - 1 ; ++next )
 {
  for ( int j = 0; j < size - 1 - next; ++j )
  {
                result = strcmp (array[j], array[j+1]);
 
                if (result > 0)
     swap ( array[j] , array[j+1] );
  }   
 }
}

and in the main i just did the cout...

This is a perfect Bubble Sort. Now all you have to work on is your formatting ;)

void BubbleSort( const char *array[] , int size )
{
 
    int result;
 
    for ( int next = 0; next < size - 1 ; ++next )
    {
        for ( int j = 0; j < size - 1 - next; ++j )
        {
            result = strcmp (array[j], array[j+1]);
 
            if (result > 0)
                swap ( array[j] , array[j+1] );
        }   
    }
}

Man! That doesn't look ANYThing like your ORIGINAL work, which was basically OK!

No it wasn't, it didn't work and the logic was wrong.

Below is my solutiion using your work.
The commented out part is how to fix YOUR original method.
The current solution uses that handy swap funtion that appeared out of thin air.

Both will work. To toggle the solutions, just uncomment the code, but be sure to comment out the swap functon.

for ( int next = 1; next < ArraySize; next++ )
{

if( (strncmp(Array[next-1],Array[next],3) ) > 0)
{

    //const char* temp[ArraySize];
    //temp[next-1] = Array[next-1];
    //Array[next-1] = Array[next];
    //Array[next] =temp[next-1];
    swap(Array[next],Array[next-1]);

    next=0;
}

You had it all along! You just needed a few tweeks!!!!

Beg to differ. Rerun your program. All it does is place the largest value in the last position. It does nothing to any other position in the array. Try again.
[OOPS]Sorry. Missed the actual reason it worked. So it does. See below.[/OOPS]

I tested both versions before i posted!
His original code is in this thread.
cut 'n paste 'n compile 'n run!
Simple, compact and a thing of beauty (if I must say so myself-LOL)

Unfortunatly, I'm not smart enough to be able to cut and paste the output terminal in codeblocks!!

Click on the far left of the title bar
Choose EDIT:MARK
Use arrow keys to highlight the section you want to cut
Press ENTER. It's now in your clipboard. Paste where you want it.

As far as why the limits? I don't know! I'm NOT the OP!
I'm just tinkering with the original to make it work as he specified.

No, we're asking you. Once you start tinkering, it's your code. If the original has a problem you must fix it, not let it stand. If you let it stand, you become a hack. ;)
And if you don't fix it, it won't work as he specified, would it?

As for my code, ther ARE two loops...sort of (no pun intended).
The reset makes it recursive , so it keeps going until there is nothing else to do! Try it..

Bad programming practice does not make a recursive function. There is no sort of in recursion. The bad practice is your reset. You might just as well use a goto and get rid of the loop. You should not adjust a loop index mid-loop. It's inexpected, bad practice, and harder to debug.

Notice my OOPS above. As a professional programmer, the last thing I expect is for someone to reset a loop counter, so I glossed over it. This hopefully will tell you something.

The Guru's have spoken!
OK, OK,!! So it's NOT the ultimate in programming, but it does work as advertised!!! That's all I'm saying about, not that it's better!

I, am NOt by ANY stretch of the imagination, a profesional programmer! I just thought it was a creative solution to an exercise.

If I knew what I was doing, i probably wouldn't have messed with that particular item as much as I did.

I didn't know that resetting the loop was taboo! Now I do...
The compiler didn't complain at all!
I suppose that "free running " programs like that are probably likely to spin out of control and have very little use in the real world of programs as does the exercise itself!

The Guru's have spoken!
OK, OK,!! So it's NOT the ultimate in programming, but it does work as advertised!!! That's all I'm saying about, not that it's better!

I, am NOt by ANY stretch of the imagination, a profesional programmer! I just thought it was a creative solution to an exercise.

Yes, it was very creative. Kudos for finding that solution. I apologize for for not saying this before....

If I knew what I was doing, i probably wouldn't have messed with that particular item as much as I did.

Good way to learn...

I didn't know that resetting the loop was taboo! Now I do...
The compiler didn't complain at all!

That's because it's a logic error, not a compiler error. As you discovered, you can in fact modify a loop parameter to alter the way the loop processes. There are cases when this is a good thing I suppose, but it's rare. There isn't a standard that says you can't, but a guideline that says you shouldn't. Kinda like chocolate covered liver. You can do it, but it's just not a good idea.

This article has been dead for over six months. Start a new discussion instead.