sort examples - numerical recipies in c

12
Chapter 8: Sorting char txt tl,laxsrRt ; aryecto!(r.NP) I if ( (rp = fopen("tarray.i::_, n!er!o' ( oDlta f e llr:-_r! fgers(rxt,uAxsrR,fp) ; for (i=1;i<-N"ri++) fscana (:. 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); l piks!2 sotu an snay, and sir:r sir€) conespondingly. In prograh i::ri tafuay.dat. The saond is dcn:€ soned and a is not. After a call Io :: !€cond call, lhis rime wilh b as ."\. ::! should b. renncd to then ongina.l a- /* Dliver for routine llxss: . *include <stdio.h> *include nxutil. h" { ch!r txrl{axsrRl; 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.-' 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 of tu dnay, 4.1 p€wlins a tuk table showidq the tuk ordet of each eletuent ih the tutuy. piksrr so.is a sr'rAle adaX by the 'thiAht insettion Eeliod. piksr2 sorts by the sme method but mat6 t}e co.respo,dj,g 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$ s sDaJI 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 'ottitg one arny ||hile makins 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 two ^rray eleaents j ard k are in l.he same equivalence 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 App€ndix to tlis chapter. The loglm prints both the original d the soned atrdy foi /i Drive! f,o! rourine Prt€RT a/ +incrude <stdid.h> 'Iinclude 'nrutiI.h { 102 /* serelate b-a!!.y 1/ for li=1;i<-NP;i++) bl:l -:-

Upload: bobdole

Post on 19-Oct-2015

41 views

Category:

Documents


3 download

DESCRIPTION

Gives examples of Heapsort and other sorts in C

TRANSCRIPT

  • Chapter 8: Sorting

    char txt tl,laxsrRt ;

    aryecto!(r.NP) Iif ( (rp = fopen("tarray.i::_,

    n!er!o' ( oDlta f e llr:-_r!fgers(rxt,uAxsrR,fp) ;for (i=1;i

  • Choptet S: Sornns 103

    roF a eariety ofso.trr r6}J incfrdirstrcPanns an iidet table fot the order.bL showits the Iank otdet ot ea.h. nale &.zy by the straisht inieltionDtethod but n*6 the cort5poailih.'Ell. shett .tu.1is our a Sie/i sori., ad they are rclsteal in the s^me \|zy::: erLs a $;ale aday; so!r2 softsbsits z se.ord athy. qcksrt sort,.htn is f.st (on zveftse) but requit5i, 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,cb r s&ord a..ay whce eieaafs ii.,ljl@@ts of the oieinel ztay...:.2 z deal with equivalence ctsses..zb ele@ent in

    ^t atay bsed @ aE a itput. ecrazz sives the sarle.d:Tiiv (i, k) which tells whethe!ree equjvala. dars.

    ,r iDsnion. Sample progam xpiks!1. c1l :airay.dat which is lisleat in fteloft lhc oliginal and rhe sorrcd alray fo.

    char t:rtldslRl;

    a4ecro! 11, NF ) tIf ((fp = fopen(italray.dat"r"!")) -- NUL')

    nrerro!(!'D,r: fils TARRAY.DAT Tot found\ni) ;fqets {txr,ldslR, rp),fo! (i-r;i

  • Chaptet 8 of Nluneicot Recipes cove6 a nietv of sottjts lasks includlngsorfine Mavs inlo nMed.al otale\ Prcpa ne M iidu table |or the otderot an *tzy, nd preparinl a t k tsble showj,8 the re* odet of Fa'helement in the ai'sy. pikslt sotts a 6irgJe drav bv the

    'traieht itsertio

    method. pikslZ sotts by the Bsme method b,t' mal6 lfie co'respotdr''stea ncenent of a seond a av 6 weli. shell

    'aries oot 2 She sott'

    sort ;d sorr2 boii do a Hedpsort, ud thev arc rclated in the same qav6 piksrt dd piks!2 Tlat i!, sort sor,s a 5j,Ele atuv; satt? sortsan t.ay while .onesPotilinSly resEzAginc s se.ond 6.ral qcksrt sortsn attzy by the Qdcksort slsorithm, which is fst (on avetaee) b& requirea small sotrnt of a]u'ltiliatv storase.

    lndelr itdxer M aftzy. That is, ii prcduc6 s seconil a$zv lh^trcferenc9 the elefunts of the oi?in\l aftav in the order oftlieit size sor!3uses index)< dd l:llus!6ts jt! vahe bv sottitc o,e dtuv while mzkins.oBsponalins retftltsements in two othes tank produ'6 the ttuk 16blefot u my il data. The tsk table is a second aftsv *hde elements lbtile rel orde. of tle co.ssponalins elements of the ot'jdal atav

    Finail,,,h rouiites eclass d e.razz deal \|ith esdealen'e clDsesecrass sives l,he equivalen e class of es.h elnent in an ttav bsed on alist of equiwlent PaiB which it is Eiven s inp\t. ec\azz cives the sameoutptr, but bates i, on a p.ocedure nded equ iv (i ,k) whi'h tells ||hethettwo arny elements j d k are in the sar,le eEtivaierce ciass'

    Routine plksrt sons an a.rr.v bv straighr insenion Smple pro8ftn xPiksrr 'c.mvides iL;irh a lo0-elemenL armv from file La!!"Y dal shich i' lisred ;n rheippendix ro rhis chaprer. Thc Pmgran Pthl' bo$ lhe original and fte soned atr'av ror

    /* Drive! tor rouline PrxsRr r/*incrude

    '*include "nrut ,h"

    I

    tu

    char txrlMAxslRl,

    a=v6cco! l1,NP),if I (fp = fopen("rallay.dat", :

    ue!!o!( lData file TARSY.::: :fqers (lxr,MAxsrR, fp) Ifor (i-1;i

  • r ar4 NM.n.aI R.ciDes Exatwl. Book/* soit a and nix b )/plintf {"\nAfter soltinqfor (i-0ri
  • :x:; b, alray a ls:\n');-r-- 2:", a t10!i+jl );

    'r_.2:",bt10ri+ll ) r

    -:E a, arraY a is:\n )t

    'tr_.2!,at10*i+iI),

    _:r-2t,bt10ti+ll);

    f a dara array. Th calling fornat is idnticalF samplc Fogram, now carbd xshell. c

    ChaDt.r 8: Somng 105piiDlr ("\tr");

    lp.tDtf (

    " \nsoltd alrav: \n") tfo! (t-0;i

  • 1ft Nut wical Recb.s Exanple Book

    Ich'i lxt li,axsrRl ,

    a{ecto!(1,NP);bTecto!(1,NP) ilf l(!P - fopen("tarlay dat","!i)) == \'vtr)

    n!6r!or{i'Dara file raRRrY.DAr not fou.d\! )tfgers (rxr, n\xsrR, fP),foi (i-1;i

  • Chqrer 8: Softin8 l0-7/* Dliwe! for toutino IlrDExx r/

    Iinclude

    *include nluti1.h"

    Icha! trttlrlxsrRltirt i, i, rindt;

    indx=ivector(1rNP';a4ectorll,NP);if {(fp - fopn("tariay.dat" r")) == NU!L)

    ".""'"'rioot. f e TABRAY.DAT no! fould\n )'faet3 ltxt,MAxsrR, f P) it;! (r-I;i

  • \ --,!-:: at::ts E ,hp|e Book

    i

    .har dumv tNlENl, amsq tNrEN+l1 , breg tN!EN+11, cnss |N!EN+11;cha! astlcpyO, *6tlcat O;

    aaector(1,NtrEN);baector(1,NLEN);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 [email protected] not found\n,,);fgets (dwy, Nr.EN, fp) ;fo! (i=1;i

  • Chapw 8: So nS 109/i Dliver for routine F.M r/

    Itnclude +includ "nrutl1.h"

    Icha! txt tlrdstRl;int i, J, *.1r *indx' *irank,f10at *a,bt11l;

    indr=rwcto! (1,NP);1lalk=ivecto! (1,NP),a4cto!l1,NP)rif {(fp = fopenl'!:rray,dat","r')) -- NUL')

    nErlor( '.Data f e TARRAY.DAT lot found\n");tgets (txt,l4AxsTR, f P),fo! ri-l; i

  • 110 NMeicaI Recipes Exa,'ple Book

    /r Dliwer fo! loutine ocKsRr */*In.Iude *irclude nrutil.h'

    Ichar txtr axsrRl;

    aaecto!(r,NP)rif ((f,p - fope! ( tarray.dat',

    ' )) == l,vl!)file [email protected] not found\n );

    fget. (txt,ltr.rsTR, fp) ;for (a=1ri

  • _!7.2fo,at10ii+il),

    -1?.2f", a tr0*i+jl ),

    f cquivarence clalses for fte elemnts of anI and tisLb Ijl which list equiyalent pai$

    ,2,6,2,7,!t,3,4,123,6,10,14,3,7,15,8,4

    5, I is cquivalert to 9, elc. Ifyou work it oDt,

    1,5,9,132,6,10,143)7,11,154,4,12

    and oughl lo sgee with this list.

    /i Drive! fo! roltiDe ECTASS */

    *include lincrude nlutil.h

    { 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,41tnf=iwectorll,N);nflag'ivector (1, N) insav=ivecto! (1, N) reclass lnf ,N, llst!, listb,M) ;fo! {1=1ri

  • I112 Nu"eical Recipes Erample Rook

    rerurD {i $.a) == (j * a);l

    Iint i/ j, */ lclas/ rclass, *nfl *nftaq/ *nsav,nf-iwector (1,N);nflaq=iwctor (1,N);nsav=ivector(1,N);eclazz (!f,N, equiw) tfor (i=1ri