• C

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;                                    
Who is Participating?
evilrixSenior Software Engineer (Avast)Commented:
Yeah, that looks like a very simple bubble sort. Thing to do is shove it into your code and see if it does what you expect.

One possible optimization is that if you managed to read all through the list in the inner loop without performing a swap the list is sorted so you cant terminate early (otherwise you'll have to wait for all iterations of the outer and inner look to complete).
evilrixSenior Software Engineer (Avast)Commented:
>> 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.
evilrixSenior Software Engineer (Avast)Commented:
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.


#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

clscor2Author Commented:
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(name[j],name[j - 1]);
               strcpy(name[j - 1],hold);
clscor2Author Commented:
Thank you!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.