Search code examples
cstringbubble-sort

I want to sort the characters in a string using bubble sort. What is wrong with this code?


/* gets a string */
printf("Enter the string: ");
scanf("%s", s);

/* finds length of the string */
while(s[size]!='\0')
{
    size++;
}

/* sorts the elements of the string using bubble sort */
for(j=0; j<size-1; j++)
{
    for(i=0; i<(size-1-i); i++)
    {
        if(s[i]>s[i+1])
        {
            temp=s[i];
            s[i]=s[i+1];
            s[i+1]=temp;
        }
    }

    /* displays pass by pass output */
    printf("\nIteration %d\n", j+1);
    printf("%s\n", s);
}

return 0;

This is the output I am getting -

Enter the string: computer

Iteration 1 cmoputer

Iteration 2 cmoputer

Iteration 3 cmoputer

Iteration 4 cmoputer

Iteration 5 cmoputer

Iteration 6 cmoputer

Iteration 7 cmoputer

Please correct the code and tell me the mistake. Thanks!


Solution

  • This

    size-1-i
    

    scan only to half of the word "cmoputer".
    That half is already sorted.

    Change to

    size-1-j