Permutations of Strings

  • + 1 comment

    Refer here : https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order

    int next_permutation(int n, char **s)
    {
        int k=-1;
        for(int i=0;i<n-1;i++)
        {
            if(strcmp(s[i],s[i+1])<0)
                k=i;
        }
        // printf("k = %d",k);
    
        if (k==-1)
        return 0;
        
        int l=-1;
        for(int i=k+1;i<n;i++)
        {
            if(strcmp(s[k],s[i])<0)
                l=i;
        }
        // printf("\nl = %d",l);
        
        
        if(l!=-1)
        {
            char* temp = s[k];
            s[k] = s[l];
            s[l] = temp;
        }
            
        //Reverse the sequence from a[k + 1] up to and including the final element a[n].
        int start=k+1;
        int end=n-1;
        while (start < end) {
          char*  temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
        
            
        
        
        return 1;
    }