Permutations of Strings

  • + 0 comments

    Tried to make is as simple as possible

    void reverse(char **s, int start, int end) {
        while (start < end) {
            char *temp = s[start];
            s[start] = s[end];
            s[end] = temp;
            start++;
            end--;
        }
    }
    
    int next_permutation(int n, char **s)
    {
        int i = n - 2;
        while (i >= 0 && strcmp(s[i], s[i + 1]) >= 0) i--; 
        
        if (i < 0) return 0;
        
        int j = n - 1;
        while (strcmp(s[i], s[j]) >= 0) j--; 
        
        char *temp = s[i];
        s[i] = s[j];
        s[j] = temp;
        
        reverse(s, i + 1, n - 1);
        
        return 1;
    }