22.02.2014 Views

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

Discrete Mathematics University of Kentucky CS 275 Spring ... - MGNet

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Generating permutations and combinations is useful and sometimes important.<br />

Note: We can place any n-set into a 1-1 correspondence with the first n natural<br />

numbers. All permutations can be listed using {1, 2, …, n} instead <strong>of</strong> the actual<br />

set elements. There are n! possible permutations.<br />

Definition: In the lexicographic (or dictionary) ordering, the permutation <strong>of</strong><br />

{1,2,…,n} a 1 a 2 …a n precedes b 1 b 2 …b n if and only if a i ; b i , for all 1;i;n.<br />

Examples:<br />

• 5 elements. The permutation 21435 precedes 21543.<br />

• Given 362541, then 364125 is the next permutation lexicographically.<br />

95<br />

Algorithm: Generate the next permutation in lexicographic order.<br />

procedure next_perm(a 1 a 2 …a n : a i ,{1,2,…,n} and distinct)<br />

j := n – 1<br />

while a j > a j+1<br />

j := j – 1<br />

{j is the largest subscript with a j < a j+1 }<br />

k := n<br />

while a j > a k<br />

k := k – 1<br />

{a k is the smallest integer greater than a j to the right <strong>of</strong> a j }<br />

Swap a j and a k<br />

r := n, s := j+1<br />

while r > s<br />

Swap a r and a s<br />

r := r – 1, s:= s + 1<br />

{This puts the tail end <strong>of</strong> the permutation after the j th<br />

increasing order}<br />

position in<br />

96

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!