CMPSCI 311: Theory of Algorithms

David Mix Barrington

Fall, 2003

Discussion Notes #6

from Wednesday 22 Oct 2003

Fun With Permutations

Please answer the questions during the discussion period.

The permutations of an n-element set are the n! different listings of it as a sequence. Here is a Java class that stores a permutation as an array of int variables with the numbers {1,...,n} in some order. The second array arrow is used in the Johnson-Trotter algorithm below.


     public class Permutation
        int n; // size of set
        int [] a; // values from 1 through n in some order
        boolean [] arrow; // true means left, false means right

     public Permutation (size)
     {// creates new identity permutation of given size
        n = size;
        a = new int[n];
        arrow = new boolean[n];
        for (int i=0; i < n; i++)
           {a[i] = i+1; arrow[i] = true;}

     public void swap (int i, int j)
     {// swaps both value and arrow in position i and j
        int ti = a[i]; a[i] = a[j]; a[j] = ti;
        boolean tb = arrow[i]; arrow[i] = arrow[j]; arrow[j] = tb;}

Last modified 22 October 2003