Problem Statement
Write a c program to sort a string in alphabetical order/lexicographical order.
Solution
#include<stdio.h>
int main()
{
char s[1000],t;
int i,j;
scanf("%s",s);
for(i=0;s[i]!='\0';i++)
{
for(j=i+1;s[j]!='\0';j++)
{
if(s[i]>s[j])
{
t=s[i];
s[i]=s[j];
s[j]=t;
}
}
}
for(i=0;s[i]!='\0';i++)
{
printf("%c",s[i]);
}
return 0;
}
Input
murali
Output
ailmru
Sort a String in an Alphabetical order/lexicographical order.
- Sorting a string in alphabetical order means the entered/given string to be arranged in an alphabetical order.
- In this c program we are going to see how a string can be arranged in alphabetical order.
- Here, we use i, j as integer variables and t, s of length size for storing characters as character variable.
- Getting the input character as string using scanf function and %s as access modifier and stored it in character variable s of fixed length as per our convention.
- After getting input using nested for loop we are checking for greater or smaller by comparing their ASCII values.
- If one of the character values is greater than other then it should immediately swapped with other using swapping of two values method by creating temp variable and storing in it then used that variable for swapping purpose.
- Do the above step till input character value reaches to NULL Value.
- If the nested for loop executed completely, now the input string become completely sorted string and they arranged in the alphabetical order.
- Now we can display the sorted string in c using printf function with the help of for loop.