954,124 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Problem in sorting by name

I am having a problem in sorting by name. for eg: if given two names Sameer and Sean, I want to print Sameer and not Sean. It needs to check character by character. I have to extend this to a greater no. of names but I need to get the basic right first. Here is the code i have written:

#include<string.h>
#include<conio.h>
#include<stdio.h>
int main(void)
{
 clrscr();
 int flag,x=0;
 char name1[20],name2[20],name3[20],ch,*ptr,*ptr2;
 gets(name1);
 gets(name2);
 flag=0;
  ch=97;
  for(x=0;x<(strlen(name1)) && x<(strlen(name2)) && flag==0;x++)
  {
   ch=97+x;
   ptr = strrchr(name1,ch);
   ptr2 = strrchr(name2,ch);
   if(ptr==ptr2)
   {
    flag=0;
   }
   if(ptr==0 && ptr2!=0)
   {
    strcpy(name3,name1);
    flag=1;
   }
   if(ptr2==0 && ptr!=0)
   {
    strcpy(name3,name2);
    flag=1;
   }
   if(ptr<ptr2)
   {
    strcpy(name3,name1);
   }
   if(ptr>ptr2)
   {
    strcpy(name3,name2);
   }
  }
 printf(" %s",name3);
 getch();
 return 0;
}

Some one pls help me out!

ankit_the_hawk
Light Poster
44 posts since Sep 2005
Reputation Points: 10
Solved Threads: 0
 

It is not good practice to use strlen in a for loop, especially for loops that must loop many times because strlen iterates through the array of characters one-by-one every time called (i.e. every loop) and takes up a lot of processor time. You could get the strlen then just used the variables.

Good luck, LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

It is not good practice to use strlen in a for loop, especially for loops that must loop many times because strlen iterates through the array of characters one-by-one every time called (i.e. every loop) and takes up a lot of processor time. You could get the strlen then just used the variables.

Good luck, LamaBot



Ya rite. thnx. I will keep that in mind. Still waiting for the solution though!:)

ankit_the_hawk
Light Poster
44 posts since Sep 2005
Reputation Points: 10
Solved Threads: 0
 
for(x=0;x<(strlen(name1)) && x<(strlen(name2)) && flag==0;x++)
  {
   ch=97+x;
   ptr = strrchr(name1,ch);
   ptr2 = strrchr(name2,ch);

What happens if a string doesn't contain a character for ascii 97 to 97+strlen in its name? If strchr encountered a character not located in the string, it'll return NULL. What if the strlen of name1 is larger than name2? You'd be checking 8 char's for name1 and matching character 97+8 to name2 which could contain only 5 char's and even then, not all the ascii char's were checked since you're checking from 97+strlen of a given name, for instance. You could do something like this:

string name1, name2;
int len = name1.length(), len2 = name2.length(), x;
for (x=0;x<len-1 || x<len-1;x++) {
 if (name1[x]>name2[x]) 
  name1.swap(name2)
}


The above uses strings and not character arrays, but it is an example. Last, you might want to convert the string to check on lower case characters in my example, because character at x might be larger in name1 if it is lowercase but the alpha character still comes before x in name2 which is a capital letter and thus will always be smaller than any of its lower case counter parts.

Good luck, LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

I think you you use Turbo C, so string class wont work with your compiler, because Turbo C++ is old compiler and supports AT&T C++ not ANSI C++.

And yes you should also not use gets() and puts() functions. Also clrscr() and getch() are also not standardised.

Here's the code. I have removed some unnecessary variables.

#include<string.h>
#include<conio.h>
#include<stdio.h>


int main(void)
{
 clrscr();

 char name1[20],name2[20];
 int *ptr;
 gets(name1);
 gets(name2);

 int s1 = strlen(name1);
 int s2 = strlen(name2);

(s1<=s2)?ptr=&s1:ptr=&s2;

 int x, flag=0;

 for( x=0;x<*ptr;x++)
 {

     int ch = (int)name1[x], _ch = (int)name2[x];  // takes one character

     if(ch<97)        {  ch+= 32; }         // converts to lowercase
     else if(_ch<97)  { _ch+= 32; }

    // if bot characters are not equal, loop is terminated.
    // flag is -1 for name2 and 1 for name2 and 0 if equal
 if(ch!=_ch)                                  
     {
       if(ch>_ch)flag=-1; else flag=1;
       break;
     }
 }

 if(flag==1)
     puts(name1); 
else if(flag==-1) 
     puts(name2); 

 getch();
 return 0;
}
vishesh
Nearly a Posting Virtuoso
1,381 posts since Oct 2006
Reputation Points: 85
Solved Threads: 42
 

Yeah.... the code I'd posted was an example. I indicated this when I said ...., but it is an example.

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

strcmp() doesn't interest you...oh well.:rolleyes:

iamthwee
Posting Expert
5,950 posts since Aug 2005
Reputation Points: 1,543
Solved Threads: 439
 

Ankit, like Iamthwee said, strcmp ( ) coupled with qsort ( ) function should work out to be fine in your case.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
 

Here is a program that might help you: http://www.daniweb.com/code/snippet660.html

Good luck, LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

>Here is a program that might help you
Somehow I kind of doubt that when the code doesn't even compile. :rolleyes:

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 
>Here is a program that might help you Somehow I kind of doubt that when the code doesn't even compile. :rolleyes:

Then I suggest you get a new compiler ;) Lol.

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

>Then I suggest you get a new compiler
I suggest that you fix the 2 typos that you made.

/* Converts upper case letters to lower case */
void toLower(char *str) {
    int len = strlen(str)-1, i;
    for (i=0;i<len;i++)
        /* 'name' has never been declared, perhaps you meant 'str'? */
        if (!(name[i]>=97 && name[i] <= 122)) 
            name[i] += 32;
}
int cmpstr(char *str1, char *str2) {
    int len1, len2, i;
    
    len1 = strlen(str1);
    len2 = strlen(str2);
    
    for (i=0;i<len1 && i<len2;i++) {
        if (str1[i] < str2[i])
            return 1;
        /* change 'str' to 'str1' */
        else if (str[i] > str2[i])
            return 2;
    }
    return 0;
}


Really, when posting code snippets, the least you can do is make sure it works under normal circumstances. The corrections I showed makes it compile and run, although the code snippet still doesn't take into account numbers.

[edit] I have made a couple of other minor fixes to your toLower() function:

/* Converts upper case letters to lower case */
void toLower(char *str) {
    int len = strlen(str), i; /* removed the -1 part... why skip the last character? */
    for (i=0;i<len;i++)
        if ((str[i]>='A' && str[i] <= 'Z')) /* only lowercases letters now*/
            str[i] += 32;
}
John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

Here is another example program that might help you:
http://www.daniweb.com/code/showsnippet.php?codeid=661

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 
Here is another example program that might help you: http://www.daniweb.com/code/snippet661.html


When will you learn? If you're going to submit code,make sure it compiles.

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 
>Then I suggest you get a new compiler I suggest that you fix the 2 typos that you made. /* 'name' has never been declared, perhaps you meant 'str'? */

Yeah, the only compiler I have access to is on a Windows workstation, which I'm not allowed to transport any data electronically. So I simply copy from the compiler IDE to the code posting. But thanks for pointing that out. :mrgreen:Really, when posting code snippets, the least you can do is make sure it works under normal circumstances. The corrections I showed makes it compile and run, although the code snippet still doesn't take into account numbers.

[edit] I have made a couple of other minor fixes to your toLower() function:

/* Converts upper case letters to lower case */
void toLower(char *str) {
    int len = strlen(str), i; /* removed the -1 part... why skip the last character? */
    for (i=0;i<len;i++)
        if ((str[i]>='A' && str[i] <= 'Z')) /* only lowercases letters now*/
            str[i] += 32;
}

Oh thanks! That is much better. I'll even make it better such as formatting :cheesy::

/* Converts upper case letters to lower case */
....
        if ((str[i] >= 65 && str[i] <= 90)) /* Only lowercases letters now???? The other one did handle lower case letters I just !=notted the result of the condition:)*/
 }


Joe, thanks for all your help....
LamaBot

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 
When will you learn? If you're going to submit code, make sure it compiles.

Umm.... Lol.... I do make sure. :lol:

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

>Only lowercases letters now???? The other one did handle lower case letters I just !=notted the result of the condition
No, I used "lowercases" as a verb. Thus, it only converts (or "lowercases") uppercase letters now, not any non-lowercase letter.

And this is just my opinion, but: I don't really see why using numbers in place of characters makes the code any clearer.

>Umm.... Lol.... I do make sure.
Being unable to compile code is not a good excuse for posting lousy code. If you are unable to check the code with a compiler, you'd be better off not posting anything. (You can actually get away with posting code with syntax errors here on the forum as long as you warn the person, but that's ONLY for the forums -- code snippets should be always compile.)

John A
Vampirical Lurker
Team Colleague
7,630 posts since Apr 2006
Reputation Points: 2,240
Solved Threads: 339
 

Lazaro, make sure your code is up to the specified standards like Joey said. I see a lot of beginner style programming which may confuse other people trying to learn the language.

for (i=0;i<len1 && i<len2;i++) {
    if (str1[i] < str2[i])
        return 1;
    else if (str[i] > str2[i])
        return 2;
}
return 0 ;
}


It should be something like: (not the exact implementation)

{
    for (i=0;i<len1 && i<len2;i++) {
        if (str1[i] < str2[i])
            return str1 [i] - str2 [i] ;
        else if (str[i] > str2[i])
            return str1 [i] - str2 [i]
    }
return 0 ;
}


though I would even modify the loop to make it better, but then again, its okay.
This is not how string comparision function works. The string comparision functions returns the ASCII difference between the strings if they are unequal while a zero if they are equal.

Why try to write a half baked comparision function when the library itself provides for its implementation.

~s.o.s~
Failure as a human
Administrator
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 733
 
>Only lowercases letters now???? The other one did handle lower case letters I just !=notted the result of the condition No, I used "lowercases" as a verb. Thus, it only converts (or "lowercases") uppercase letters now, not any non-lowercase letter.

Well considering the context of this debate, any considerate person would clarify such a deceiving addition.And this is just my opinion, but: I don't really see why using numbers in place of characters makes the code any clearer.

Yeah.... well it is a good thing it is your opinion. :lol:>Umm.... Lol.... I do make sure.
Being unable to compile code is not a good excuse for posting lousy code. If you are unable to check the code with a compiler, you'd be better off not posting anything. (You can actually get away with posting code with syntax errors here on the forum as long as you warn the person, but that's ONLY for the forums -- code snippets should be always compile.)

Lousy code? Lol, um ok. You tell that to my colleague who happen to see me swiftly write the code and who checked it. As I specified earlier, as you seemed to have ignored, it did compile sucessfully. Perhaps not on the Linux machine I'm on now, but it did on the XP box, but I can just look the code over to make sure. :) You should be more considerate when make such absolute claims.

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

Well if he is learning then he is a beginner. So what is your point?

Lazaro Claiborn
Junior Poster
171 posts since Jan 2007
Reputation Points: 11
Solved Threads: 13
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You