Search code examples
carrayssortingcharbubble-sort

Comparing char array elements


I'm trying to arrange this character array that only contains digits,it prints the same array with the order I input it without any change , i tried using type casting in the if statement, it gave me correct results when running but it wasn't accepted by the online judge.what is the fault here and why isn't my second solution accepted?

#include <stdio.h>
#include <string.h>
int main() {
    char x[101];
    scanf("%s",x);
    int l,i,j ;

    l = strlen(x);

    char temp ;

    for(i=0;x[i];i++)
    {
        for( j=i ; x[j] ; j++){

            if('x[j]'<'x[i]') //(int)x[j] and (int)x[i] didn't work on the 
                               //online judge
            {
                temp=x[i];
                x[i]=x[j];
                x[j]=temp;

            }
        }
    }

    printf("%s",x);
    return 0 ;
}

Solution

  • I have no idea why there are quotes around the array elements, but that is not doing what you think, the comparison is happening because a multicharacter string is evaluated to an integer value which is implementation defined, hence the if statement is always comparing the same values, which means that it will always give the same result, you need to remove the quotes

    if (x[j] < x[i])
    

    Also, i'd recommend specifying the length of the array to scanf() and checking that it successfuly read the value, like this

    if (scanf("%100s", x) != 1)
        return -1; /* Perhaps EOF, i.e. you pressed Ctrl+D or (Ctrl+Z MS Windows) */
    

    If you don't check your program will invoke undefined behavior, and if here it doesn't hurt any critical part of your simple program, if you don't learn to do it, then you will have a lot of hard do debug bugs in the future when you write a bigger program.