Wednesday, May 6, 2009

PROGRAM FOR SORTING THE GIVEN STRINGS

/* take a set of strings as input from command line and
load them into an array of strings and print
the sorted list of strings.
*/
#include
#include
#define BUFSIZE 64
char *strings[BUFSIZE]; /* array of pointers to hold strings */
main()
{
char temp[BUFSIZE]; /* temporary string to hold user input */
int i=0; /*index into the strings list */
/* this loop runs till user inputs END */
/*initialize the strings to nulls */
for(i=0; istrings[i]=NULL;
i=0;
while(1)
{
/* zerofill temp to avoid any garbage later */
memset(temp, 0, BUFSIZE);
/* ask the user to give string input */
printf("enter a string. enter END to stop input:");
/* take user input into temp */
scanf("%s", temp);
/* compare user input with END.
if
equal to zero exit the loop and go to sort
else
get memory (size=BUFSIZE) to the next string pointer
load the string into the memory
*/
if(!strcmp(temp, "END"))
{
break;
}
if(NULL==(strings[i]=(char *)malloc(BUFSIZE)))
{
/* memory allocation failed */
perror("malloc():");
exit(0);
}
/* copy the string into strings list */
strcpy(strings[i], temp);
i++;
} /* while */
/* strings list */
//for(i=0; strings[i]!=NULL; i++)
// printf("%s\n", strings[i]);
/* now that we have got our list. Need to sort it
*/
for(i=0; strings[i]!=NULL; i++)
{
int j;
char *p; /* temp pointer */
for(j=i+1; strings[j]!=NULL; j++)
{
// printf("%s\n %s\n", strings[i], strings[j]);
if(strcmp(strings[i], strings[j])>0)
{
p=strings[j];
strings[j]=strings[i];
strings[i]=p;
}
}
} /* for */
printf("sorted list is .............\n");
/* print the ordered list */
for(i=0; strings[i]!=NULL; i++)
{
printf("%s\n", strings[i]);
}
}

No comments:

Post a Comment