Académique Documents
Professionnel Documents
Culture Documents
Chapter 8: Sorting
Chaptet 8 of NME.ical Recipes cove6 a htiety of Bottiig t6ks itLluding solti's asay' ijlto numerical orde4 prcp^dns ai] itdex tabie lot the o et
for (i=1;i<-N"ri++)
ordet of each insettion 'thiAht co.respo,dj,g Eeliod. piksr2 sorts by the sme method but mat6 t}e rcatsngement of s second NEy I w . shell ca.des out a SIeiJ sort. so!! ed so!t2 borl do z Heapsott, nil they ate rebte.l in the szme way arpiksrt and piksr2. Tla, ir, sorr soris a sirgle aiay; sart2 softs n *By whjb cotrespondhsly rearugina z secord a.!a/- qcksll 6orts s st2{ by the Qubksott alsolithm, ||h;ch is fst (on avetae) blt rcqrb$
fscana
(:.
of
tu
dnay,
eletuent
ih the tutuy.
piksrr
showidq
the
tuk
printf (i6rig1!at alray: \r-) : fo! (i-0;i<=9ri++) I fo! {j=1; j<-10; j++) r=::: plinrf(.\n');
I
printf (i3olted array: \ni) ; fo! (i=0;i<-9;i++) { for (j=1; j<-10; j++) .::i: plinrft"\n"); l
free_wect6!(a,1,NP);
eoura of aqiliary sto.age. indexx indses e aEs.". Ttut is, it peducg 3 Beond atay th^t rcferen es the elements of the oici8l atay jn the otalet of thei Eite. sort3 s6 indexx ud;iist.af6 its vaJue by one arny ||hile makins 'ottitg cotft'ponaling retttusements in two othe6. tank prcilnc5 the tuk table fot e dray of data. The tdk tabie is a stord aiay wh6e elenents lirt the tuk orde! of the co spon lins elements of the otislnzl anay. Iinalit the rortirB ec l as s ard e claz z deal witl eq ujvaler.e .les6. eclass sjv6 tie equivalen.e cla$ of $ch elenent in tu atay based on a lbt of eryivalent pai's whjc,h it i, siven as jnput'. eclazz sjv6 the s^me output but bB6 it on s prc.eduE need equiv ( j, k) which telb ehethet
s sDaJI
two
piks!2
tafuay.dat.
sir:r i::ri ::
dcn:
!cond call, lhis rime wilh b as ."\. ::! should b. renncd to then ongina.l a-
^rray
eleaents
ard k are in
cls.
Routrn pikslL so.ts an army by stnight insenion. Sa..nple proSram xpikslL . c provides it with a l0o-elernent army ftoln file tarray.dat which is listed in rhe Appndix to tlis chapter. The loglm prints both the original d the soned atrdy foi
ch!r txrl{axsrRl;
'Iinclude 'nrutiI.h
aryecto'{1,NP); b+ector (1,NP); if { (fp = fopen("talray.d::_ nrerror (iData f e ta:-:-rl fget3 (rxr,ldsrR, fp), fo! (i=t,i<>NP;i++) fsca.r.-'
Choptet S:
Sornns
103
char t:rtldslRl;
a4ecro! 11, NF ) t If ((fp = fopen(italray.dat"r"!")) -- NUL') nrerro!(!'D,r: fils TARRAY.DAT Tot found\ni) ; fqets {txr,ldslR, rp), fo! (i-r;i<-NPri++t f6carf (fp,.,if ,eatll) j
roF a eariety ofso.trr r6}J incfrdirs trcPanns an iidet table fot the order .bL showits the Iank otdet ot ea.h . nale &.zy by the straisht inieltion Dtethod but n*6 the cort5poailih.
Printf ( " ortgtnal alray: \n.) t fo! li=0ii<-9ri++) I fo! ( j-1; j<-10; j++) priltf 1"*?.2f"/at10li+jl plintf {i\ni);
,
shett .tu.1is our a Sie/i sori. 'Ell. , ad they are rclsteal in the s^me \|zy ::: erLs a $;ale aday; so!r2 softs bsits z se.ord athy. qcksrt sort, .htn is f.st (on zveftse) but requit5
plintf ("sorted a!!ay: \!"), ro! (i=0,i<=9,i++) { for (J-1rj<-10rj++) printf (',*7.2f," a t10*i+jl Plintf ('\n"),
flee_wecto!{a,1/NP),
I I
i, iI pbdu. a 6qoDd trcJ thst |fr-viD ite order of tlreir e',e. softl ! bt s.titA one t$y \|hite tua|ins xr6. .anK prcducg tle.et ia6,c
b r s&ord a..ay whce eieaafs ljl@@ts of the oieinel ztay.
ii.,
..:.2 z deal with equivalence ctsses. .zb ele@ent in atay bsed @ a ^t sives the sarle E a itput. ecrazz .d:Tiiv (i, k) which tells whethe!
plksr2 sor6 an aray, and simultaously rcarr.ngcs a sc.ond aray (of rhe sane !ize) corrcspondingly. In Fograrn xpi ksr2 . c, the first arny a t i I is again sten ftoln tarlay.da!. Thc second is defined by blil=i-1. In othcr words, b is originally soned ald a is not. After a call to piks!2. thc snuation should be Evencd. With a second call, this timc with b as thc tust arguncDt ard a as thc !.con4 dle rwo arrays should bc rlumed to fteir original fom. /t Dliver fo! rourine
linclude <stdio.h>
PrxsR2
*/
ree
,r
equjvala. dars.
+include.'n!utiLh"
1l :airay.dat
loft
xpiks!1.
which is lisleat in fte lhc oliginal and rhe sorrcd alray fo.
cha! txttr4AxsrRt,
brector l1,N?); if ((fp = fopen{"tar!ay.daro, ili) ) -- trvrr,) nre!!o!(iDara file fAFRAy.DAT nor found\n,,), f,gets ( rrt , rrlxsTR, fp ) ; for (i-r;i<-NP,i++) fscanf (fp,,'tf., [a ti] ) I
aryecto! (r,NP);
char txrlMAxslRl,
a=v6cco! l1,NP),
if
fqers (lxr,MAxsrR, fp) I for (i-1;i<=NPjt++) fscanf (fp, -i:sorfine Mavs inlo nMed.al otale\ ot an *tzy, nd preparinl a t k tsble showj,8 the re* odet of Fa'h itsertio element in the ai'sy. pikslt sotts a 6irgJe drav bv the 'traieht lfie co'respotdr''s mal6 b,t' Bsme method pikslZ by the sotts method. tea ncenent of a seond a av 6 weli. shell 'aries oot 2 She sott' qav do a Hedpsort, ud thev arc rclated in the same
Chaptet 8 of Nluneicot Recipes cove6 a
nietv of sottjts lasks includlng Prcpa ne M iidu table |or the otder
priDtf ( oEiginar array:\!, ) ; for (!=0;i<-9;i++) ( for (l-1;j<-10;j++) priDt: {"!_ pltncf('\n );
)
sort ;d sorr2 boii 6 piksrt dd piks!2 Tlat i!, sort sor,s a 5j,Ele atuv; satt? sorts an t.ay while .onesPotilinSly resEzAginc s se.ond 6.ral qcksrt sorts n attzy by the Qdcksort slsorithm, which is fst (on avetaee) b& require
a small sotrnt of a]u'ltiliatv storase. lndelr itdxer M aftzy. That is,
I
printf('sorted array: \n') r f,ox (i-ori<=9ri++) { for (j=lr j<:10, j++) prtntf("i_ prinrf ("\tr") | flee
)
wect.or(a,1,
NP)
rcferenc9 the elefunts of the oi?in\l aftav in the order oftlieit size sor!3 uses index)< dd l:llus!6ts jt! vahe bv sottitc o,e dtuv while mzkins .oBsponalins retftltsements in two othes tank produ'6 the ttuk 16ble fot u my il data. The tsk table is a second aftsv *hde elements lbt ile rel orde. of tle co.ssponalins elements of the ot'jdal atav Finail,,,h rouiites eclass d e.razz deal \|ith esdealen'e clDses ecrass sives l,he equivalen e class of es.h elnent in an ttav bsed on a list of equiwlent PaiB which it is Eiven s inp\t. ec\azz cives the same outptr, but bates i, on a p.ocedure nded equ iv (i ,k) whi'h tells ||hethet d k are in the sar,le eEtivaierce ciass' two arny elements j
piksr2 sons an aEay, and simultarcous: size) corrcspondingly. In progrdm lpi k s.: . The second is defined by a: sorted ud a is not. Afler a call io piks:2, second call, this time with b as thc 6!sr a$u should bc retumcd to fteir oriSinal fom.
tarray.dat.
/*
Dxiwer
for rourine
PrKsR2
r/
*include <stdio,h>
*incrude "nruti1.h"
Routine
.mvides ippendix ro rhis chaprer. Thc Pmgran Pthl' bo$ lhe original and fte soned atr'av ror
plksrt sons an a.rr.v bv straighr insenion Smple pro8ftn xPiksrr 'c iL;irh a lo0-elemenL armv from file La!!"Y dal shich i' lisred ;n rhe
PrxsRr
char txtt!{AxsrRl,
r/
a{ector{1,NP);
b=wector(1,NP);
if I(fp = fopeD("tarray.dat , :' nre!!o!("Data file !ARR.4Y.r;: fget3 (ttt,wsrR, fp) ; for (i=1;i<=NPr i++) fs.anf{f!, /t genelat b a!!ay
tu
ar4
NM.n.aI
/* soit a and nix b )/ plintf {"\nAfter soltinq a ald nn*1ng b, atray a ie:\n ), for (i-0ri<=9;i++) { for (l=1rj<-10;j++) plIntf ("8?.2f raIlOri+jl ) ; plIntf("\n... and alray b ia:\n )r f,o! (i=0ri<-9r1++) | fo! lj=1;j<=10, j++) pliltf ("*? 2f",bt10li+il), printf("pless letuln !o conttnu ...\n ), /r 3o!t b and frix a l/
I
)
prlntf ("\D"t,
)
prinrf ( n \nsolted alraY: \n"); for li'07i<-9;1++) ( for (j-r;j<-10; J++) PEintr (-t: printf("\n ), l f!e_wector { a, r. NP) i
I
By the sanc token, mutines sort and s . : and piks!2, res?ccdvely. Both ru howcvcr, works on a single array. soil2 so
piksrt
.eenanScmcnts lo a sccond.
printf {"\r fter sorting b and nixing a, atay a is:\nr')i fo. (i-0;i<=9;i++) { for (J=1rj<-10tj++) plintf ("t].2f ,a110ri+jl ) ;
soRr
*/
Printf("\n,.. and alrav b i3:u )r for ti=0;i<-9j1++) I for (j=l;j<-1ot j++) Prhtf ('N?.2f"rbtt0ii+Jl);
p!in!f {tr\ni) I
(r,, 1,
NP )
fiee_vectoi
I
f*e_vecto!(a,1,NP);
cha! t*ttMAIsrRl,
Proccdurc shell do.s a Shell son of a alAta army. The cauing fomat is id'ntical to that of ptksrt, and so we u!. th sane ssmple pmgram' now called tshell c'
SIIELT
r/
aryector (1,NP),
(fP - fopen("talray.dat",":-) nrelro!i!'Data file TARFIY,lAa fgets{tar,MrxsTR, fp), for (i-I;l<-NPr l,++) f.canf lfp, -i:'
if
printf { '\no!191na1 airaY: \n"); fo! (i-0;i<-9;t++) I fo! (J=1, j<=10; j++) printf('iprtntf( \n ), l printf ("\Dsolted array: \n"); fo! (t-0ri<=9r1++) { fo! (1-1, i<-10, j++) Printf('iPrintf (i\ni) ' ) f!e_vector{a,1.NP) i l /) DllweE foi xoutine soRt2 */ linclude <stdio.h> |include "nrutil.b
chax
t*t fMuslRl,
a+ecto! (1,1rl); if (lfp - fopen("tarrav dat","r')) =- NU!t') nre!!o!l!'Data file raRRlY DAr not found\n");
fgets {tat.rrAxsrR, rP) ; fo! ti,ljj<=Np;i++) fscanf (fp, "*f",
("
&a
ti));
ChaDt.r 8:
Somng
105
piiDlr ("\tr");
l
p.tDtf ( " \nsoltd alrav: \n") t fo! (t-0;i<=9t1++) I ;o! (i-1tj<-10;j++t Printf("i? 2f"' a llOri+jl ); plintf {"\n )t f*e-vecto!(a,1.NP);
I I Bv rhe sme token. roulines
'r_.2:",bt10ri+ll
)r
sorr
and
solt
t""pc.tjvelv Bo$ "'*.'.i "J"rt"'2, ."1i' * ,i"eti a-"v.'so'tz i.*.1* " rearangmenls to a scotrd /* Dltver f,o! loutile soRr */ *ilcrude <atdlo.h>
*inc1u66 "nrltif.h"
2 enplov Lhe sane progarns as routines roudnes usc fi Heapsorl alsorithm so,!L' while makins correspondins sons one
"'rav
*defi@
MAXSTR 30
_:r-2t,bt10ti+ll);
I
cha! t*ttlraxsrRl;
a dara array. Th calling fornat is idntical samplc Fogram, now carbd xshell. c
a4ecto! (1.NP) t -- trrurl) tf ((fp = fo!!lrrtarlaY.dat","!")) file TaRRAY DAT not found\!"); ""e.to"tioott (txt,tL'J<SrR, fP) : fcers ror rr-:; i.+rp, i''r fscanf{Ip,"Xr",talii)i plintr( \nollginal arlaY: \n") i fo! (i-0ri<-9ri++, { ;o! (J=1;j<-10;j++) Plinlf ("*7'2f"' al10ri+il ) ' prhtf ( '\n"l i
I
plintf {"\nsorted aEaY: \n )r for (i=0;1<=9;1++) ( ;o! (j-1;j<-1orj++) plintf ("t? 2f"'atl0ri+jl); prinlr ("\!");
flee_vector{a,1,NP);
I
1ft
Nut
aiDclud "nrutil.h"
a{ecto!(1,NP); bTecto!(1,NP) i lf l(!P - fopen("tarlay dat","!i)) == \'vtr) n!6r!or{i'Dara file raRRrY.DAr not fou.d\! )t fgers (rxr, n\xsrR, fP), foi (i-1;i<-NPri++) frcanf lfp, "tf", &a Iil ); /r senlate b-arlay */ fo! {1-1ii<-NF:i++) blil-i-1; /r solt a and nix b */ prinrf{i\nafter 3orting a and eiaing br array a i6:\n'); for (t-0r1<-9ri++) ( fox (j-l;j<-10,J++) prlntf( t?.2f'r al10ri+jl ); priitf("\n"l; printf('\n... and alray b is:\D ), fo! (i-0ri<-9;i++) I fo! (J-1,1<=10r j++) p!1rtf ("t?.2f",b110*i+jl ), pllntf ("\n ), plintf(ipless
I
sort2 (N?,a.b),
ind!-iwector (1r NP) i aryector(1,NP), if I(fp - fopen("t,!ray.dat", ! )) nrlro!1"!ara fife laRiaY.DAr fgets ltat,wsrR, fp) , fo! (i=1ri<=rri++) fscanf (fp, talndexx iM, a, in.lxl ; plintf l"\loriqinal alray: \n"); ror (t-0ri<=9ji++) { for (J-1,J<-10rj++) Printf p!i!tf (i\n");
I
("
i'-
retlln to contlnue. .. \D ) I
a
printf l " \nsorted array: \tr"), fo! (i=0;i<=9ri++) I fo! (j=1,j<=10;j++) piincf ( i: pltnrf( \n )t flee wecto!(a,1,NP), free iwecto! (Indx. t, NP),
)
prinrf({\dfre! solting b and nixinq a/ arlay a Is:\n )r fo! (1,0,i<-9,i++t I fo! (j-1,j<=10rj++) piintf ('17.2r', a t10*i+jl ); prinrf(i\n..- and a!!ay b i3:\n ); fo! (i-0;i<-9,i++) I for ( j=1; j<-10, j++) pllntf ("t?.2f ",bf10*i+jl Printf {"\t');
l flee_vctorlb,lrNP), flee_vctor (a/ lrNP);
I
Plintf
li\ntr);
)r
Tllc procedu& indexx gEncralcs lho index array for a given input aFay. Th index array indx I J I 8ivcs, for cach j, ftc indcx of fic lncnt of fte input aray which will assume posilon if thc array is sonen. That is, ftr an input amy a, the sorted version of a will bc a l indx t j I l . Ib d.momlatc this, sanple progam xindexx c produces an indcx for thc anay in tarlay.dat. It lhen prints $e ajray in the oder j=1, ..,100 for inspcction.
Onc use for indexx is lhe managcmcnt l ampl, sons one afray while making corEspo sarnplc gogram xsort3 . c, thc fir$ array il lay . daL (scc Appndix). The sc.ond ed thj 64 in forward order ard ryerse odet, csp.ct sccond and third arc scrambld" but scranblcc a text message is assiSnd to a charictcr a@!... rc the order of nlmbe found in tne rcnn"nl unscrambled according !o the order of nhb< so!t3 worki properly, lhis ought to leaYe ft
soRr3
r/
allndxtJll,
"nrut
.h
Chqrer 8:
Softin8
l0-7
cha! trttlrlxsrRlt
irt i, i, rindt;
u:ig
b, auay a is:\n.'),
a
a4ectorll,NP); if {(fp - fopn("tariay.dat" r")) == NU!L) f e TABRAY.DAT no! fould\n )' ".""'"'rioot. f faet3 ltxt,MAxsrR, P) i t;! (r-I;i<_NPii+-, fscanf(!p, *! 6aL-l'r
lndexx{NP,a,t!<tx);
(_*t.2r",
I10ii+jl ),
(_
r7.2f", btr0ri+jl );
print.f("\noligina1 array: \n") I fo! li-0ri<-9;i++) I iot tj=rti.=rO, j**l printf ("t7 2f"'atr0*t+jl)' Plintf ("\n"); I printf ("\nsolted array:\!") i foi (i-0;i<=9ri++) { ;o! (j-l, j<-ro, j++) plintf("t? 2r"alindxtl0*i+rlI); printf ("\D ''; l free vector lar l,NP)t fle_iwectoi indx, 1,lP ) ;
I
{_*t.2f,a{10*1+Jl);
_!-.2!", btr0*i+jl );
two orhc' arravs ln .'." *r'rle making i-omsponding reorderinS\ of64 *Di* t.* cle'nents or La!first """ *1".: c, rrre nis anav is rakcn as the "',.i.i. tt'e rumbers rro to be ""--taken an amvs ud rnird il"'.iiii'* a""J-,. n'e second fie lilsr anav ls o'uereo
r+ in rward or&l md rcverse order' Especrjvelv Wlten .Ine sav ro prole rnrs' imond atd Lhird are scrambLed" bur scranbled in exacLlv rhe salnc *''g""a ,o a chamctcr anav Then the leners e scranbled accordins rhe) aJe sbsequendf " "i*i,*"* *.bir' round in dre rcamnsed *cond ar-dv l ir'" thiid alrav lf reanangd ".1*1r **.J"g. t'" ordr of nu'ntcrs found in the ir"rt"rn^ura order'
given input aray. The indx r&r of thc elemert of thc input aray which td That is, fd an input aFay a, rhe soned honstrntc !his, sanple program xindexx. c ry..iar- Il lhcn prints rhe array in rhe older
a
id.x
afay for
iit, i'il*;ii' tt't' oush! to reavc the messase """iil */ /. Dliver for routiDe soRr3
ainclude <stdio.h> *inclnde <Gth.h>
Itnclude "t!ui11.h"
--,!-:: at::ts
E ,hp|e Book
*incrud <stdio.h>
linclude "nrurII.h,
*define niaSTR 30
c{ector (1,NrEN); (woid) stlcpy(ansg, .r.d lattrer nawe a botrle in frort ofi); {void) strcat (afrss, " re than a fronral loborony..); p.iltf ( \ro.isinar hessaqe:\nts\n,arcq) ; /i iead array df randon nun$ers */ if ((fp - fopen("ta!ray-dat",,'! )) -= NUlt ) nlerior(iDara fite laI@y.DAr not found\n,,); fgets (dwy, Nr.EN, fp) ; fo! (i=1;i<:Nr,EN; i++) fscanf (fp, !9f,, da {il); /r .leate a!!ay b and ar.ay c r/ fo! (i-lJ i<=N!EN;i++) {
c )
aaector(1,NtrEN); baector(1,NLEN);
cha. txrurixsrRl,
indr=tvector(t,Np); irank:ivector {1,Np); a=vecrortr/NP), if ((fp = fopen{"talraY.;:-. nrerror("Data fil :::-:"_1i rl fgets (txt,l{AxslR,fp) ; for (i-r;i<=NP;i++)
rank(NP,lndx,irank); printf ( o.iqinal f,or li=0;i<=9ri++) I for (j-r; j<=10; j++) !::::: plintf (o\n");
lndexr(NP,a, indr),
lit=NrEN+1-r;
for (i=1ri<-NrENri++)
bcstt
l
1l=ansqrj 11,
priltf("table of ranks rs: : for {i-0;i<=9;i++) { for (j=1; j<=10; j++) :::::: pri,tf ("\n");
plintf(
)
prese
cneq) ;
ptintf (ia!!ay sorted acc.::r1: : for (i=0;i<=9;i++) { for lj=1;j<-10Jj++) i k=10*i+ir for tr=1; I<=NP;:-if (ilankilj == . : fo! lj=l; j<=10; j++) !:r1-,: plintf {o\n"); free wectoi(a,1, Np); flee iwecto! lilank, r, Iin, ) ;
f.ee_iwect or (indx,1, NP);
I
)
rank is a lNedure that is simild ro indexx. Insread of prodocing an indexing anay, Ihough, it produces a mnt rable. For an aray a t j I and rant tabre i rank { j L enry j in ilank will rell eha! index aljl will haye if a is soned. ilank acba y lakes its input infomation not ftom the anly itsell but ftom tte index day lroduced by indexx. Sample prcgran riank. c begins with rle array fiom talray, dd feeds it rc index: d rank. The table of ranks produced is lisred. To check ir, the may a is copied inro an aray b ir the rank order suggested by irank. b should then be in
qckslt
like that of
Chapw 8:
So nS
109
lobotony. !') t
ir f,ront of,),
f10at *a,bt11l;
1lalk=ivecto! (1,NP), a4cto!l1,NP)r -- NUL') if {(fp = fopenl'!:rray,dat","r')) nErlor( '.Data f e TARRAY.DAT lot found\n");
tgets (txt,l4AxsTR, f P), fo! ri-l; i<-Np;!++) fscanf {fp, "*f", ta til ); indexa{NP,arindx),
ralk(NP, indxr irank) t printf ("originaf a!!aY i3:\n ), fo! li=0;i<=9tt++) { for {j=1; j<-10, j++) printf ("*?.2f ,at10ri+jl); printf ("\ni);
prlntf("table of lanks ts:\n ); ro! (i=0ri<-9ii++) I fo! (j-1, j<=10, j++) plinlf l"t7d",iraDk{10ri+jl )' printf (i\n")t p'intf("pless leturn to continue.. \n ), ;!intf("a!!ay solted accordirs to lank table:\!"); fo! ti=0; i<=9;i++) { for lj'l;j<=10,j++) I k=10*i+jj for {1-r; I<=NP;r++) if lilankrll _- k) bljl-alll; l fo! (j-1t j<_1oi j++) prhtf("t? 2f',blJl); Prhtf("\!");
l
ir u a.ray a t J I and rdik rablc tlank I j L : t: *iI have if a is soned. irank actually
EraI i6clf, but fton lhe indcx aray produced hgir5 widr the array ftom tarlay, and feeds E.ks pDduccd is lisred. To chck it, the army d.r suggested by irank. b should then be in
I
::.iexx.
flee-iwector{in&,
like dlat of
ree_iwector(1!a'k, 1,NP),
1,NP) ;
qcksrc sons an aEay by lhe Quickson arSorithm trs calling squence is exacdv piksrt and so!t, so we again rely on the same sample progam' now callcd xqcksrt.c
110
NMeicaI
ocKsRr
*/
*irclude nrutil.h'
char
txtr axsrRl;
in! i, i,k,Iclas,lclaEs, rnt,r.::r;, srar:ic int fista l l -10,1,1, s.2,;,:, lisrb |]=t 0/ 5r 9,13,5,10,1{,
_:
for (a=1ri<'i.lP;i++) fscanf (fPr "tf"r ta til ); plintf ("\noriqinal a!!ay:\n ), for (i=0ii<=9i1++) { for lj-1;j<-10, j++) plintf ("*7.2f ,a110*i+jl), printf (i\n"),
l
file
;
' TAI@Y.DAT
))
nf-ivecto! (1, N) ; nfraq=ivecror (1,N), nsav-ivecro!(1,N); e.Iass (nf ,N, 1i5ta, ristb,!) ; for (i-1;i<-N;i++) nflaqlil =1; printf (i\NDnlbers fron 1 td d:r:* printf(itheir value frodulo 4:,: :' for (i-1;i<=Nri++) { rclass=nfttl; lf {nflastnotas6l )
nfraqtncrasst =0t
plintf li'\rso!!ed arlay: \n"), f.r (l_0ri<=9ri++) { for (j=1rj<=10,j++) printf plintf ("\n'),
free_veclor (a,1,
I I
NP )
("
t7.2f"
/a
I10*i+j! ),
for (j=i; j<=Nr j++) if (Dfljl : nftr:) priltf( cla33 *2d: for (J=r, J<-k; j++) pr:::: plintf ("\n") ; l
f
hocdure eclass grneratcs a list of equivalence clalses for ftc elements of an inputaray,ba!.donthearrayslistaljlandtisrbljl which lilt qlivalent Pairs for each j. In sarnplc program xeclass.c, ftese lists are
I
ree-ivecto!(n3aw/ 1rN),
lista:
I,1,5,2,6,2,7,11,3,1,12
5,9,13,6, rO, 14,3,
7, 15,
tisrb:
E,4
According to rhcsc lisrs, I is equivalent io 5, you Pill find the fo owing cl scs:
wo* it
out,
ecrazz pcrfo.ms fte sane ana.lysis bln function equiv(i. j) that tells wbcrlH: In xeclazz. c, equiv is defined a5 :i:-:
sane. It is othevise FALSE.
The sarnpl program prints out the classes and ought lo agre
witl
this list
{
ECTASS
*/
int i' j, k,]clas/ncrass, *nr. *nf1as, *.3av; srarlc inr lista ll -{0,1,r,5,2,6,2,1.t7.3' 4,12) ' Iistbtl-10/ 5r 9r 13,6,10,14t3t 1,\5,4,41t
nf=iwectorll,N); nflag'ivector (1,
nsav=ivecto!
eclass lnf ,N,
(
N)
llst!, listb,M) ; fo! {1=1ri<-Nr1++) dfraqtil =1r pdntf " \!Nunb!s fron 1-*d divided sccoldinq to\n /N); printf( theix walue rcdulo 4:\D\n");
_!7.2fo,at10ii+il),
(1, N) r
nf1a9t!classl -0;
-1?.2f",
tr0*i+jl ),
I
for li=ir j<_N; j++) if (!ftjl -_ nftil) nsawl++kl=jt ir1c1a3) , plintf ("cla.s t2d: ("t3d",nsav ljl ); (j-t;l<=t,j++) prlntf fo! printf ("\n") t
l fle_ivctor(nsaw, 1,N); free iwector(nfragr1,N) ; f,!ee,tvector{nf ,1,N},
I
cquivarence clalses for fte elemnts of an which list equiyalent pai$ and tisLb
Ijl
,2,6,2,7,!t,3,4,12
3,6,10,14,3,7,15,8,4
5, I is cquivalert to 9, elc. Ifyou work it oDt,
fDnction
eclazz perfons fte same dalysis but figuEs thc e4uivarncls from a boolean equiv ( I , j ) that tells whelher i and i are in fte samc quivalence class' Inxec]azz.c, equlv is {tefined ar TRuE iJ (i MoD 4) and (J MoD 4) @ the
same. It is othefwigc FALSE.
Eclazz
*/
*include <stdio.h>
*incllde "nruti1.h"
I
112
Nu"eical
l
I
nsav=ivector(1,N);
for (i=1ri<=N;i++) nfraq Iil =1; printf ('\nNuidrers f rom l-Sd divided a.cordinq to\r", pltntf ('lheir value nodulo 4r\n"), for (i-l;i<*N;i++) nclass-nftil; if (nflaglnclassl ) I nflagtn.lassl-0;
1
N)
ing toots to eguatiors, ed trca:: : dimersioh. we beqin with a sere:. ptuducs a c.tde gnph af a cj'i. :
:.
ceometically until
( j-i; j<'N; j++) if (nfljl == nftil) nsavt++kt=j; pxintf{"crassg2d: ",1clas); for (j=1rj<=k, j++) printf ("t3d",nsavljl), Printfl \n );
for
it btuckets z tu.1 N subintetfrIs of eq@l size. It 1:.: lest one tuot. Once bracteted, ..:1
.outio.s.
method of f.lse position an l the .ombin'tion of methods to sire
used tot l@-t6ol\tion plattitg tc : tion. With th;s in hand, 9|e adi .The ffBt of th6e tzk6 a furctio" a.:
rtneil
for frndins the rcots of pol!t.= bined with its dilet zraa',s it c{ complex coefrcbnts. whe' ,ou .al rca] polynomial, they cM be poli::.:
In multjpie dr'mensiotu,
.@t'n:.
!eiEhbata.,'..
13.42 5:.10 34.36 99.33 33.46 3r.59 99.34 92.22 94.29 ?.03 5.6? 39.3s 2.95 8s.02 9s.32 13.96 49.29 71.12 1.47 9.4e 32.31 89.9s 28.39 ?9.36 11.t1 14.33 74,73 4,62 49.95 63.44 42.44 64.14 49.41 52_99 1t.19 3.94
t5.22
.c:
or
/*
scissa'
lincllde <sldio.h>
Btatic froat fx(x)
{
retud bes3j0{r);