The following algorithm is given and we are supposed to write it out in java. However, when I try to understand line by line, it gets confusing, especially the part:
A[k+1:N-1] = the values in S in ascending order
To my understand, the set only have 1 number at anytime. How can we replace A[k+1:N-1]
when the set only has 1 number?
Let A be a sequence of integers 0
to N-1
in ascending order (let's assume its an array of int[N]
).
next_permutation(A):
k = N-1
S = { }
while k >= 0:
if S contains a value larger than A[k]:
v = the smallest member of S that is larger than A[k]
remove v from S
insert A[k] in S
A[k] = v
A[k+1:N-1] = the values in S in ascending order.
return true
else:
insert A[k] in S
k -= 1
return false
The algorithm shown is similar to the Generation in lexicographic order. You can read the article for further information.
This is not needed. You can try to keep the S array sorted all the time. Every time you want to insert a new number in the array, you insert it in such, so the array could stay sorted. For example, if you have
S = [5 7 8]
so far and you want to insert6
, you inserted between 5 and 7 -S = [5 6 7 8]
. This way the replacement step is just copying the elements from S to A[k+1:N-1].