Link to home
Start Free TrialLog in
Avatar of clscor2
clscor2Flag for United States of America

asked on

What is argsort?

I have an assignment where I need to do an argsort of 5 words.  It was suggested that I should use strcmp to compare strings to sort in alphabetic order.  So, this is what I have right now, but do I need to add something to sort these???
#include <stdio.h>
#include <string.h>      

 
int main(int argc, char *argv[]) {              
    int i = 0;                                  
    char word[128] = "";                        
   
 
 
      while (word >= 1) {
            printf("Enter a word (-1 to end):\n");
            scanf("%s", word);      
      }

    for (i = 0; i < argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
 
    return 0;                                    
}
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

>> but do I need to add something to sort these???
Is it the arguments in argv you want to sort? If so you can implement a simple bubble sort to do this (there are plenty of examples if you Google "Bubble Sort". Your sort algorithm will need a comparator function (a function to compare 2 strings and return which is greater) and for this you can, as you observe, use strcmp.

Have a go at implementing this... post back if you get struck.
BTW: if your assignment isn't to actually write a sort routine you could use qsort to do the sorting. You can still use strcmp to provide the comparator (since qsort can take a user defined function to do the comparing); however, it's signature is slightly different from strcmp so you'll have to write your own function that wraps strcmp.

http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/

#include <stdlib.h>
#include <string.h>
 
// Your comparator
int comparator ( const void * lhs, const void * rhs) {
	return strcmp((char const *)lhs,(char const *)rhs);
} 
 
int main(int argc, char * argv[])
{
	// Calling qsort with your comparator to sort argv
	qsort ( argv, argc, sizeof(char *), comparator  );
}

Open in new window

Avatar of clscor2

ASKER

So, if I added something like this.....

 for (i = last ; i > 0 ; i--)
         for (j = 1 ; j <= i ; j++)
            if (strcmp(name[j],name[j - 1]) < 0) {
               strcpy(hold,name[j]);
               strcpy(name[j],name[j - 1]);
               strcpy(name[j - 1],hold);
ASKER CERTIFIED SOLUTION
Avatar of evilrix
evilrix
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of clscor2

ASKER

Thank you!