Search code examples
csortingpointerssuffix-array

sorting suffixes by qsort


I am trying to sort suffixes of a string by qsort() but not getting the sorted list .

what should i do ?
Here is what i have done :

char str[MAXN]="banana", *a[MAXN];

for(i=0;i<strlen(str);i++)
   a[i]=&str[i];  //a[] points to suffixes starting

qsort(a, n, sizeof(char *), compare);

this is my compare() function :

int compare(const void* p, const void* q)
{
     char *a= (char*)p;
     char *b= (char*)q;

    return strcmp(a,b);
}

a[i] points to i'th suffix of str = "banana"
a[0]: banana    
a[1]: anana    
a[2]: nana    
a[3]: ana
a[4]: na
a[5]: a

after qsort() i want to get :

a[0]: a
a[1]: ana
a[2]: anana
a[3]: banana
a[4]: na
a[5]: nana

the problem is that i am getting unsorted list.


Solution

  • The compare function receives pointers to items in the array. Since the array items here are pointers to char, what it receives is pointers to pointers to char:

    int compare(const void* p, const void* q)
    {
         char **a= (char**)p;
         char **b= (char**)q;
    
        return strcmp(*a,*b);
    }