Stack Overflow
Stack Overflow

Reputation: 11

Unable to sort the character array using bubble sort in C

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.

Upvotes: 1

Views: 70

Answers (1)

BLUEPIXY
BLUEPIXY

Reputation: 40145

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)

Upvotes: 1

Related Questions