1

I am trying to sort an array of characters in C but it prints out the same array instead of the sorted

char*P[5] = {"1c", "4h", "3g", "10g"};
total_items = 4; // number of elements in the array. 

for(int q =1; q<total_items; q++)
{
    for(int k=0; k<total_items-q; k++)
    {
        if((int)P[k]>=(int)P[k+1])
        {
            temp=P[k];
            P[k]=P[k+1];
            P[k+1]=temp;
        }
    }
}

When I print out the array, it's the same as the original. I tried debugging by printing in the if statements; it turns out it never enters the swap block of the code. Is there something I am missing?

The expected output should be 1c, 3g, 10g, 4h.

11
  • 1
    Use strcmp instead of >= (>). Commented May 25, 2017 at 19:03
  • @BLUEPIXY : Hi, would you be able to edit this for me? I tried using strcmp and it prints out the whole array in the opposite order, not sure where I am going wrong here :\ Commented May 25, 2017 at 19:06
  • 1
    Read strcmp Commented May 25, 2017 at 19:08
  • @StackOverflow You should be able to write the condition based on the return value of strcmp. Commented May 25, 2017 at 19:09
  • @Mahesh : could you please edit my solution and post it as an answer? Commented May 25, 2017 at 19:10

1 Answer 1

1

Create your own comparison function.

like this :

int cmp(const char *a, const char *b){
    int ai, bi;
    char ac, bc;
    sscanf(a, "%d%c", &ai, &ac);//Separate number and letter
    sscanf(b, "%d%c", &bi, &bc);
    if(ac > bc)
        return 1;
    else if(ac < bc)
        return -1;
    return ai < bi ? -1 : ai > bi;
}

then Replace if((int)P[k]>=(int)P[k+1]) with if(cmp(P[k], P[k+1]) > 0)

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, thank you so much. Just another point of enquiry, the code fails when I try to run it with different array such as {1a 1c 2a 2f 1d}, it outs 2a 1d "whitespace" 2f. Any idea to why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.