Algorithm for generating permutations

Source: Internet
Author: User

Dictionary Ordering method

For the arrangement given in the Order of dictionaries (p=p (1) P (2) P (3) p (4) ... p (n)), the algorithm for generating the next permutation from one permutation is as follows:

(1) The maximum value of J to satisfy the relationship p (j-1) <p (j) is set to I, i.e. i=max{j|p (j-1) <p (j)}

(2) To satisfy the relationship of P (i-1) <p (k) The maximum value of K is set to J, that is J=max{k|p (i-1) <p (k)}

(3) P (i-1) and P (j) interchange position, get P ' =p (1) P (2) ... p (n)

(4) in P ' =p (1) P (2) ... p (i-1) p (i) p (i+1) p (n), the P (i) p (i+1) ... p (n) in reverse order, the resulting p=p (1) P (2) ... p (i-1) p (n) p (n-1) ... p (i) sequence is the request. The meaning of J is the subscript of the permutation, for an arrangement with n number, the range of J is from 0 to N. P (j) is the number of the first J of this arrangement.

Attached Source:

Var

P:array[0..1000]of Longint;

I,n,j,k,t:longint;

Begin

READLN (n);

For I:=1 to n do p[i]:=i;

Repeat

For I:=1 to N do write (P[i], "); Writeln;

For J:=1 to N does if p[j-1]<p[j] then i:=j;

For K:=1 to N does if p[i-1]<p[k] then j:=k;

T:=P[I-1];  P[I-1]:=P[J]; p[j]:=t;

For K:=i to (i+n) SHR 1 does

Begin

T:=P[K]; P[k]:=p[n-k+i]; p[n-k+i]:=t;

End

Until I=1;

End.

Algorithm for generating permutations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.