U .e@sdZddlTddlZGdddeZGdddeZdd Zd d Zd d Z ddZ ddZ d%ddZ ddZ ddZddZddZddZddZd d!Zd"Zd#Zed$kreZedS)&a sorting_animation.py A minimal sorting algorithm animation: Sorts a shelf of 10 blocks using insertion sort, selection sort and quicksort. Shelfs are implemented using builtin lists. Blocks are turtles with shape "square", but stretched to rectangles by shapesize() --------------------------------------- To exit press space button --------------------------------------- )*Nc@s,eZdZddZddZddZddZd S) BlockcCsF||_tj|ddd|||ddd|d|dS)NZsquareF)shapeZvisibleg?black)sizeTurtle__init__Zpu shapesize fillcolorst)selfrr2/usr/lib64/python3.8/turtledemo/sorting_animate.pyr s  zBlock.__init__cCs|ddS)NZredr r rrrglowsz Block.glowcCs|ddS)Nrrrrrrunglow"sz Block.unglowcCs d|jS)NzBlock size: {0})formatrrrrr__repr__%szBlock.__repr__N)__name__ __module__ __qualname__r rrrrrrrrsrc@s<eZdZddZddZddZddZd d Zd d Zd S)ShelfcCs||_d|_dS)z.create a shelf. y is y-position of first blockijN)yx)r rrrrr +szShelf.__init__cCsP|\}}}|dd}||j|||jdt|||dS)Nr")r setyrsetxrlenappend)r dwidth_y_offsetrrrpush0s  z Shelf.pushcCs0||dD]}|\}}||dq dSNrposrr ibZxposr$rrr_close_gap_from_i8s zShelf._close_gap_from_icCs0||dD]}|\}}||dq dSr'r(r*rrr_open_gap_from_i=s zShelf._open_gap_from_icCs,t||}||d|||S)N)listpoprrr-)r keyr,rrrr1Bs    z Shelf.popcCsb||t|||||jd||\}}}|dd}||j||dS)Nrrr) r.r0insertrrr rrr)r r2r,r#r$r%rrrr3Is  z Shelf.insertN) rrrr r&r-r.r1r3rrrrr)s rcCs\t|}td|D]D}|}|dkrD||j||djkrD|d}q||||qdS)Nrr rangerr3r1)shelflengthr+ZholerrrisortSs  r9cCsjt|}td|dD]N}|}t|d|D]}||j||jkr,|}q,||kr||||qdS)Nrr4r5)r7r8jZiminr+rrrssort\sr;cCsn||}|||||}t||D].}||j|jkr(|||||d}q(|||||SNr4)r3r1r6r)r7leftright pivot_indexZpivotZ store_indexr+rrr partitionfs r@cCs>||kr:|}t||||}t|||dt||d|dSr<)r@qsort)r7r=r>r?Zpivot_new_indexrrrrAqs rAcCsttttd}t|t|D]@\}}t|ttD](}t|j |dkr@t |t |q@q*t t t tddtdS)N r4line) disable_keysclearr0r6randomZshuffle enumerater srr3r1 show_text instructions1 instructions2 enable_keys)targetr+tr:rrr randomizexs   rPcCs(d|}tdd|t|ddddS)Nrricenter)ZCourierZbold)ZalignZfont)Zgotowrite)textrDrrrrJsrJcCs@tttdtttttttddtdS)NzSelection Sortr4rC)rErFrJr;rIrKrLrMrrrr start_ssorts rUcCs@tttdtttttttddtdS)NzInsertion Sortr4rC)rErFrJr9rIrKrLrMrrrr start_isorts rVcCsLtttdttdttdtttttddtdS)NZ Quicksortrr4rC) rErFrJrArIr rKrLrMrrrr start_qsorts rWcCs(tdad}|D]}tt|qdS)Ni8) r r4rB)rrIr&r)Zvalsr+rrr init_shelfsr_cCs,tddtddtddtdddS)NrIr+qr)onkeyrrrrrEs   rEcCs6ttdttdttdttdttddS)Nr+rIr`raZspace)rbrVrUrWrPZbyerrrrrMs     rMcCs@ttttttttddtt dS)Nr4rCZ EVENTLOOP) Z getscreenZ clearscreenZhtZpenupr_rJrKrLrMZlistenrrrrmains  rczApress i for insertion sort, s for selection sort, q for quicksortz spacebar to quit, r to randomize__main__)r)__doc__ZturtlerGrrr0rr9r;r@rArPrJrUrVrWr_rErMrcrKrLrmsgZmainlooprrrrs,*