Next_permutation

for (int i = n - 1; i > 0 and flag == 0; i–)
{
int j = i - 1;
if (arr[i] > arr[j])
{
sort(arr + (j + 1), arr + n);
auto ub=upper_bound(arr+i,arr+n,arr[j]);
swap(*ub, arr[j]);
sort(arr + (j + 1), arr + n);
printArray(arr, n);
flag = 1;
}

        if (i == 1 and flag == 0)
        {
            sort(arr, arr + n);
            printArray(arr, n);
            flag = 1;
        }
    }

here, in this part of the code : I start my loop from i=n-1 , j= i-1, and compare if a[j]<a[i] , if this statement is true then the swapping is done and next_permutation is generated , however if it is not true , means that a[j] was >= a[i]… if this is so, then nothing is done , we do i-- and j=i-1 again and again check for a[j], a[i]… so until we get a ‘j’ for which a[j] < a[i] … the previous ones must be in decreasing order only…like a[j] <a[i] >=a[i+1] >= a[i+2] >=…a[n-1]

now please tell , what is wrong?

thank you , this last code works perfectly, i hadn’t checked for n=1; now it’s fine , thankyou

ok cool…
…

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.