permutation non recursive - Gaolious/algorithm GitHub Wiki


// to make DESC
// 121132
//    ^ 
// 
// wlneeb
//
int setNext(char str[], int n)
{
    char c;
    int l = n-1;
    int r = n-1;
    // 122341
    //   ^
    while ( l > 0 && str[l-1] >= str[l] ) l--;
    if ( l == 0 )
        return 0;
    
    while ( str[l-1] >= str[r] ) r--;
    
    c=str[r];str[r]=str[l-1];str[l-1]=c;
    
    for ( r = n-1 ; l < r ; l++, r--)
    {
        c = str[r];
        str[r] = str[l];
        str[l] = c;
    }
    return 1;
}