I'm trying to design an algorithm that sorts given words alphabetically like a dictionary but it seems that I can't progress any further

Viewed 52

First of all, I'm sorry if this isn't an appropriate question to ask. I only recently started to learn to code so it could be something obvious that I'm missing, I'm sorry about that too.

When given the words "seal", "snake", "lion"; the output is "seal sion lnake". I tried analyzing the algorithm by hand but couldn't figure out the problem. If someone could help me out, I'd really appreciate that.

#include <stdio.h>

int main()
{
    int n;
    int i;
    int j;
    int k=0;
    int l;
    char word[100][100];
    char tmp;
    
    printf("Enter the number of words ");
    scanf("%d", &n);
    
    for(i=0; i<n; i++)
    {
        printf("Enter the word ");
        scanf("%s", word[i]);
    }
    
    for(i=0; i<n-1; i++)
    {
        for(j=i+1; j<n; j++)
        {
            while(word[i][k]==word[j][k])
            {
                k=k+1;
            }
            if(word[i][k]>word[j][k])
            {
                for(l=k; l<100; l++)
                {
                    tmp=word[i][l];
                    word[i][l]=word[j][l];
                    word[j][l]=tmp;
                }
            }
        }
    }
    
    for(i=0; i<n; i++)
    {
        printf("%s ", word[i]);
    }
    
    return 0;
}

0 Answers
Related