You are given a set of words over the lowercase English alphabet. They are to be sorted in alphabetical order.
Alphabetical order : It is the order in which words are organized in a dictionary or in an telephone directory.
For example,
abc comes before xab. Reason : The first letters differ. So, they are compared. a comes before x in English alphabet.
aab comes before abc. Reason : The first letters are same (aab abc). So, the next 2 letters are compared (aab abc).
aab comes before aaba. Reason : The first 3 letters in aab are same as the first 3 letters in aaba and there are no more letters in aab to compare against aaba. So, the word with the smaller length comes first (aab).
Input - The first line has ‘n’, the number of words, followed by n lines each of which contains a word.
Output - Words in alphabetical order, one one each line.
Constraints : 0 < n <=100, 0 < length of each word <= 10
#include <stdio.h>
Alphabetical order : It is the order in which words are organized in a dictionary or in an telephone directory.
For example,
abc comes before xab. Reason : The first letters differ. So, they are compared. a comes before x in English alphabet.
aab comes before abc. Reason : The first letters are same (aab abc). So, the next 2 letters are compared (aab abc).
aab comes before aaba. Reason : The first 3 letters in aab are same as the first 3 letters in aaba and there are no more letters in aab to compare against aaba. So, the word with the smaller length comes first (aab).
Input - The first line has ‘n’, the number of words, followed by n lines each of which contains a word.
Output - Words in alphabetical order, one one each line.
Constraints : 0 < n <=100, 0 < length of each word <= 10
#include <stdio.h>
#include <string.h>
int main()
{
int num, i, j, result, index;
char name[100][11];
char temp[11];
scanf("%d", &num);
for(i = 0; i < num; i++)
scanf("%s", name[i]);
for(i = 0; i < num; i++)
{
index = i;
for(j = i + 1; j < num; j++)
{
result = strcmp(name[index], name[j]);
if(result > 0)
index = j;
}
strcpy(temp, name[index]);
strcpy(name[index], name[i]);
strcpy(name[i], temp);
}
for(i = 0; i < num-1; i++)
{
printf("%s\n", name[i]);
}
printf("%s", name[i]);
return 0;
}
No comments:
Post a Comment