Sort strings in dictionary order in C

Sort strings in dictionary order  in C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* Swap function to swap the strings starting addresses of the pointer to strings*/
void swap(char **x,char **y)
{
   char *temp;
   temp=*x;
   *x=*y;
   *y=temp;
}

/* Function to compare two strings */
int compare(char *s,char *v)
{
   while(*s && *s==*v)
    s++,v++;
   return (*s-*v);
}

int main(void) {
   char *s[10];
   int i,j;
   for(i=0;i<10;i++)
   {

    /* Memory allocation for 10 strings */
     *(s+i)=(char*)malloc(sizeof(char));

     /* Get the input word from the user */
     scanf("%s",*(s+i));
   }

   for(i=0;i<10;i++)
   {
     for(j=i+1;j<10;j++)
     {

      /* Sort the strings in alphabetical order */
      if(compare(*(s+i),*(s+j))>0)
      {
        swap((s+i),(s+j));
      }
     }
   }

   /* Print the sorted strings */
   for(i=0;i<10;i++)
    printf("%s\n",*(s+i));

   return 0;
}

Share this post


Comments (0)

  • Be first to comment

Leave a comment

or to Comment

Contact Us

  • Address: # 650 Narsi Village Sector 32 Urban Estate Karnal-132001 Haryana, India

  • Phone:(+91) 97289-77666   Email: codethor84@gmail.com


Follow Us