Sorting of strings in alphabetical order

Program 37) Write a program that would sort a list of names in alphabetical order.


A program to sort the list of strings in alphabetical order. It employs the method of bubble sorting.

                                   PROGRAM

#define ITEMS 5
#define MAXCHAR 20
main ( )
 {
        char string [ITEMS] [MAXCHAR], 
                dummy [MAXCHAR] ;
        int i = 0, j = 0 ;
      /* Reading the list   */
      printf (" Enter names of %d items \n ", ITEMS) ;
      while (i < ITEMS) 
           scanf ("%s", string [i++]) ;
     /*  Sorting begins  
     for (i =1; i < ITEMS; i++)   /* Outer loop begins */
     {
          for (j=1; j<= ITEMS - i; j++)  /* Inner loop begins  */ 
          {       
                if  (strcmp (string [j - 1], string [j] > 0)
                {  /*  Exchange of contents  */
                   strcpy (dummy, string [j - 1]) ;
                   strcpy (string [j - 1], string [j] ) ;
                   strcpy (string [j], dummy ) ;
               }
         }  /*  Inner loop ends  */ 
     }   /*   Outer loop ends  */
       /*  Sorting completd   */
       printf ("\nAlpphabetical list \n\n") ;
       for (i =0; i < ITEMS; i++)
          printf ("%s", string [i] ) ;
  }


Output:         Enter name of 5 items
                      London  Manchester Delhi Paris Moscow

                     Alphabetical list
                     Delhi
                     London
                     Manchester
                     Moscow
                     Paris 

Note that a two dimensional array is used to store the list of strings. Each string is read using a scanf function with %s format. Remember, if any string contains a while space, them the parts of the string after the white space will be treated as another item in the list by the scanf. In such cases, we should read the entire line as a string using a suitable algorithm. For example, we can use gets function to read a line of text containing a series of words. We may also use puts function in place of scanf for output. 
          
            

No comments:

Post a Comment