c-----------------------------------------------------------
c Chapter 16: The Cycle Structure of a Permutation(p144)
c-----------------------------------------------------------
c   Name of subroutine: CYCLES
c
c   Algorithm:Count cycles, find sign of a permutation
c             tag and/or invert.
c
c   input:  n=10  
c   complier: f77 cycles_2.f
c-----------------------------------------------------------

        parameter(n=10)
        integer n, sign, ncycl, option, sigma(n) 
        option=0
        write(*,10)
10      format('Input the value of the permutation')
        read(5,*), (sigma(i),i=1,10)
        call cycles(sigma,n,sign,ncycl,option)
        write(*,30) sign,ncycl,(sigma(i),i=1,n)
30      format(1x,i4,3x,i4, 3x,10i3) 
        stop
        end

c-----Subroutine begins here--------------------------------

	SUBROUTINE CYCLES (SIGMA, N, SIGN, NCYCL, OPTION)
	INTEGER SIGMA(N), SIGN, OPTION
	IS=1
	NCYCL=N
	DO 5 I=1,N
	I1=SIGMA(I)
6	IF (I1 .LE. I) GO TO  7
	NCYCL=NCYCL-1
	I2=SIGMA(I1)
	SIGMA(I1)=-I2
	I1=I2
	GO TO 6
7	IF (OPTION .NE. 0) IS=-ISIGN(1, SIGMA(I))
5	SIGMA(I)=ISIGN(SIGMA(I), IS)
	SIGN=1-2*MOD(N-NCYCL, 2)
	IF (OPTION .GE. 0) RETURN
	DO 10 I=1, N
	I1=-SIGMA(I)
	IF (I1 .LT. 0) GO TO 10
	I0=I
15	I2=SIGMA(I1)
	SIGMA(I1)=I0
	IF (I2 .LT. 0) GO TO 10
	I0=I1
	I1=I2
	GO TO 15
10	CONTINUE
	RETURN
	END

