Saturday, 28 April 2012

C Program for Sorting the Characters of a String


#include<stdio.h>
#include<conio.h>

int findlen(char str[]);
void sort(char s[]);

void main(void)
{
   char s1[80], s2[80];
   int length;
   strcpy(s1, "What the phuck?");
   strcpy(s2, "Is anything wrong with you?");

   printf("Original: %s\n", s1);
   sort(s1);
   printf("Sorted: %s\n", s1);

   printf("Original: %s\n", s2);
   sort(s2);
   printf("Sorted: %s\n", s2);

}

void sort(char s[])
{
  char tmp;
  int i, j, length;
  length=findlen(s);
  for(i=0; i<length-1; i++)
  {
 for (j=i+1; j<length; j++)
 {
    if (s[i] > s[j])
    {
   tmp=s[i];
   s[i]=s[j];
   s[j]=tmp;
    }
 }
  }
}

int findlen(char str[])
{
   int i;
   for(i=0; i<80; i++)
   {
  if(str[i]=='\0')
  {
     return(i);
  }
   }
}

No comments:

Post a Comment