Thursday, 31 March 2016

Sorting and Searching; String Sort

Write a program to sort strings using C

/*
Enter successive lines, pressing Enter at the end of each line.
Just press Enter to end.
this
is
a
c
program
to
sort
strings

Your input sorted in order is:
a
c
is
program
sort
strings
this
to

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define TRUE  1
#define FALSE 0
#define BUFFER_LEN 240
#define NUM_P 50

int str_in(char **);          /* Function prototype  */
void str_sort(char *[], int); /* Function prototype  */
void str_out(char *[], int);  /* Function prototype  */


/*execution starts here */
int main()
{
   char *pS[NUM_P];            /* Array of string pointers          */
   int count = 0;              /* Number of strings read            */

   printf("\nEnter successive lines, pressing Enter at the end of each line.\nJust press Enter to end.\n");

   for(count = 0; count < NUM_P ; count++)  /* Max of NUM_P strings   */
     if(!str_in(&pS[count]) )               /* Read a string          */
       break;                               /* Stop input on 0 return */

   str_sort( pS, count );                   /* Sort strings           */
   str_out( pS, count );                    /* Output strings         */
}

/*****************************************************
 *      String input routine                         *
 *  Argument is a pointer to a string pointer        *
 *  which is char**                                  *
 *  Returns FALSE for empty string or if memory not  *
 *  obtained, and returns TRUE otherwise.            *
 *****************************************************/
int str_in(char **pString)
{
   char buffer[BUFFER_LEN];    /* Space to store input string  */

   if(gets(buffer) == NULL )   /* NULL returned from gets()?   */
   {
     printf("\nError reading string.\n");
     return FALSE;             /* Read error                   */
   }

   if(buffer[0] == '\0')       /* Empty string read?           */
     return FALSE;

   *pString = (char*)malloc(strlen(buffer) + 1);

   if(*pString == NULL)        /* Check memory allocation      */
   {
     printf("\nOut of memory.");
     return FALSE;             /* No memory allocated          */
   }

   strcpy(*pString, buffer);   /* Copy string read to argument */
   return TRUE;
}

/****************************************************
 *      String sort routine                         *
 * First argument is array of pointers to strings   *
 * which is of type char**.                         *
 * Second argument is the number of elements in the *
 * pointer array ?i.e. the number of strings       *
 ****************************************************/
void str_sort(char *p[], int n)
{
   char *pTemp = NULL;        /* Temporary pointer               */
   int i = 0;                 /* Loop counter                    */
   int sorted = FALSE;        /* Strings sorted indicator        */
   while(!sorted)             /* Loop until there are no swaps   */
   {
     sorted = TRUE;           /* Initialize to indicate no swaps */
     for( i = 0 ; i<n-1 ; i++ )
       if(strcmp(p[i], p[i + 1]) > 0)
       {
sorted = FALSE;      /* indicate we are out of order    */
pTemp= p[i];         /* Swap pointers p[i]              */
p[i] = p[i + 1];     /*               and               */
p[i + 1]  = pTemp;   /*               p[i + 1]          */
       }
   }
}

/****************************************************
 *      String output routine                       *
 * First argument is an array of pointers to        *
 * strings which is the same as char**              *
 * The second argument is a count of the number of  *
 * pointers in the array i.e. the number of strings *
 ****************************************************/
void str_out(char *p[] , int n)
{
   int i = 0;                /* Loop counter               */

   printf("\nYour input sorted in order is:\n\n");
   for (i = 0 ; i<n ; i++)
   {
     printf("%s\n", p[i]);   /* Display a string           */
     free(p[i]);             /* Free memory for the string */
     p[i] = NULL;
   }
   return;
}

Another way to sort Strings in C language

/*
Enter successive lines, pressing Enter at the end of each line.
Just press Enter to end.

this
is
a
program
written
in
c
to sort
strings


Your input sorted in order is:

a
c
in
is
program
strings
this
to sort
written
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_LEN 100  /* Length of input buffer    */
#define NUM_P 100       /* maximum number of strings */
#define TRUE  1
#define FALSE 0

void main()
{
   char buffer[BUFFER_LEN];    /* space to store an input string    */
   char *pS[NUM_P] = { NULL }; /* Array of string pointers          */
   char *pTemp = NULL;         /* Temporary pointer                 */
   int i = 0;                  /* Loop counter                      */
   int sorted = FALSE;         /* Indicated when strings are sorted */
   int last_string = 0;        /* Index of last string entered      */

   printf("\nEnter successive lines, pressing Enter at the"
                   " end of each line.\nJust press Enter to end.\n\n");
   while((*gets(buffer) != '\0') && (i < NUM_P))
   {
     pS[i] = (char*)malloc(strlen(buffer) + 1);
     if(pS[i]==NULL)           /* Check for no memory allocated     */
     {
       printf(" Memory allocation failed. Program terminated.\n");
       return;
     }
     strcpy(pS[i++], buffer);
   }
   last_string = i;            /* Save last string index            */

   /* Sort the strings in ascending order */
   while(!sorted)
   {
     sorted = TRUE;
     for (i = 0 ; i < last_string - 1 ; i++)
       if(strcmp(pS[i], pS[i + 1]) > 0)
       {
         sorted = FALSE;     /* We were out of order */
         pTemp= pS[i];       /* Swap pointers pS[i]  */
         pS[i] = pS[i + 1];  /*       and            */
         pS[i + 1]  = pTemp; /*     pS[i + 1]        */
       }
   }

   /* Displayed the sorted strings */
   printf("\nYour input sorted in order is:\n\n");
   for (i = 0 ; i < last_string ; i++)
   {
     printf("%s\n", pS[i] );
     free( pS[i] );
     pS[i] = NULL;
   }

}


No comments:

Post a Comment