clscor2
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;
}
#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;
}
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/
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 );
}
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);
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Thank you!
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.