0

Here I am trying to use inbuilt sort function. 's' is the array which stores the index. I am trying to sort this array according to suffix strings. If I am using qsort() function it works fine. But as soon as sort() used it sorts simply s array, doesn't recognize sort according to the suffixes in str. Please suggest me suitable changes for sort function. qsort() function is denoted in comment. here is my code

    string str;
    int s[50005];
    long long l;

//for qsort()

int cmp(const void *a,const void *b)
      {
       return (strcmp((str+ *((int*)a)),(str+ *((int*)b))));
      }

//for sort() this does not works fine

int cmp1(int a,int b) 
     {
        return (strcmp((str.c_str()+ a),(str.c_str()+ b)));
      }

code for suffix array

    void suffix_array(int n)
    {
        int i;
//initially 's' is initialized with all index
        for(i=0;i<n;i++) 
           s[i]=i;

   // qsort(s,n,sizeof(int),cmp); this works fine
        sort(s,s+n,cmp1);

    }

main function

    int main() 
    {
        int n,c;
        scanf("%d",&n);
        while(n--) {
            cin>>str;
            //scanf("%s",str);
            l = str.length();
            suffix_array(l);

            for(int i=0;i<l;i++)
              cout<<s[i]<<" ";

        }
        return 0;
    }
NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    Since you are using C++ I strongly suggest you get with the times and use `std::sort` and a lambda or functor for the comparison function. – NathanOliver Jun 27 '16 at 12:06
  • except for all other issues with the code, qsort uses a compare function that returns neg, zero or pos as returned by e.g. strcmp, while std::sort uses a comparison function object that returns false or true as normally returned by operator<. – stefaanv Jun 27 '16 at 12:22
  • Could you elaborate what you want to tell ? @NathanOliver – user5228835 Jun 27 '16 at 21:12

0 Answers0