,/, ‘. J..i!l I. T,I ‘1 )I,1_/, ,‘I ’ 1.1’ I’ ‘. /,,1 stools for Web-Based Sorting Animation ’ ‘Herbert L. Dekshem ‘Depafitie’kit of Computer Science j /./., “,Hbpe College ’ Holland, MI 49422-9000 dershem@cs.hope.edu Peter Brummund Department of Computer Science Taylor University Upland, IN brummund@taylor.edu Abstract There is a long and rich tradition of sort algorithm animations that have been used effectively in instruction. This paperdescribesa new tool that combinesthe best of this tradition with the advantagesof being in the form of an applet for useon the World Wide Weband of animatingthe codeof the algorithm in concert with the animation of the data. In addition, this tool facilitates student-designedanimations that are useful for the debuggingof student-writtensort algorithms. Recursivesort algorithms are mademore accessible through the use of a special feature of the tool that animates the recursion. 1. Introduction Animation of sort algorithms has a long history in computer science education, starting with the Sorting Out Sorting video in 1981 [l]. This video introduced the idea of representingdata elementsin a sort by bars with length of the bar correspondingto the sort key value of the element. It also used highlighting to indicate elementsbeing comparedand concludedwith a race of the nine algorithms examined. Algorithm animation can be coupledwith code animation by including a separatewindow or frame wherethe codefor the algorithm is found. Animators using this techniquehighlight the line of code being executedin the algorithm simultaneously with the algorithm animation activity. This permits studentsto see how the execution of program code correspondsto the stepsof the animation.This coupling with code animatiorrhas been implementedin JCAT[6] using pseudocode, ZStep 95[7] using LISP, and in AdaVision[8] using Ada. I Systemsof algorithm animation that facilitate user-designed animationsare a more recent innovation. This approachhas recently been advocatedas pedagogically advantageousby Stasko[9]. The project describedin this paper addsthe recent advances of web access,code coupling; and user design to the proven features of the Sorting Out Sorting video, resulting in an effective tool for teaching and learning sort algorithms. In addition, an animation techniqueis addedto enhancestudent learning o$how recursion occursin sorting algorithms. 2. The Sort Animator ‘Appilet Sorting Out Sorting set such a high standardthat as algorithm animation systemssuch as GAIGS [2], Tango [3], and Balsa [4] were developed, they focused on animations of algorithms other than sorting, although sorting animations weredevelopedin all of these.None of thesepresenteda significant improvement over Sorting Out Sorting beyond their flexibility to work on user-provideddata. The advent of the World Wide Web and Java applets has openedup a new era for algorithm animations, permitting remote interactive accessto such animations with platform independence and an ability to link animations to text, sound, and video[5]. Most algorithm animation systemsare presently either on the web or in the processof migrating there. Permission to make digital/hard copies of all or part ofthis material for personal or classroom use is granted without fee provided that the copies NC not made or distributed for profit or commercial advantage, the copyright notice, the title ofthe publication and its date appear. and notice is given that copyright is by permission of the ACM, Inc. To copy othenvise, to republish, to post on servers or to redistribute to lists, requires specific permission and/or fee. SIGSCE 98 Atlanta GA USA . Copyright 1998 0-89791-994-7/9812..%5.00 222 The Sort Animator is a Javaapplet that provides a split window showing the sort animation in the left frame and the codeanimationin the right frame.The basic structure of Sort Animator is illustrated in Figure 1. The vertical bars in the left frame representthe elementsto be sortedwith the horizontal coordinateshowing the position or index of the elementin the sort list and the vertical coordinaterepresentingthe magnitudeof the element’ssort key. As the algorithm executes,the bars move as data movement occurs in the sort list. The line of code being executed at eachpoint in time is highlighted inside ,theright frame. <.’ The user hasmany controls over this animation, all of which can be modified at any point of the algorithm’s execution. The usermay specify five different colors to the sort animator, using buttons in the upper left ‘portion of the window. These specify the backgroundcolor for the sort animation, threebar colors, andthe-colorusedto highlight lines of code. The bar colors are for bars that are presently being inspected Applet _-__ __. ackground -_..__ -._~-_-.__-----_~_-__-~_-Sorted Foreground lnspectlon ._-_._ Highlight ___.._# of Blockr -_ Arrangement Speed = 1 Fotfcounter = 0; countercsize: countertt) C For(countet2 = 1: counter2 c (size -countei): counted+ iKnumarrayLcounter2-ll > numarray[count&D f temp = numerrayfcounter21 numarray[countenl = numarray[counteR-13: nqmarrayCcounter2-111 temp; 3 3 3 1Sort Control Stop Control # of Comparisons # of Swaps Explanation Algorithm 1Applet started. Figure 1. Sort Animator View by the algorithm, those that are already in their sortedposition, and thosethat fit into neither of thesecategories.These four colors may be ‘modified at any time during the animation without disrupting the algorithm. The user may also specify the number of elementsbeing sorted. This number may be as large as 900. The arrangement of the data can be random, ascending,or descending, dependingon the user’s selection. Changing the number of blocks or the arrangementresultsin an immediatehalt of the presentsort executionand a restartwith the new parameterin force. The speedcontrol is in the upper right comer of the window and managesthe speedof the animation. A slide bar determines the speedof the algorithm. If the speedis set to zero, the algorithm comes to a temporary halt. By manipulating this bar appropriately the user can observethe algorithm in detail by stepping&rough under mouse control or by nmning the algorithm at a very slow speed.Once the,user has graspedthe generalapproachof the algorithm, a fasterspeed can be selectedfor completion of the algorithm. High speed animation may also enhance algorithm understanding by giving a better overview of the sorting strategy.: . ” The execution of the algorithm is controlled by the two buttons in the lower left portion of the window. The “Sort” but223 ton begins the sort animation and its label changes to “Pause” when the animation is active. The “Stop” button halts the Soit with no possibility of resuming the interrupted sort, although anothersort can be initiated following “Stop” button selection. ’ ‘, , ,, *: When the explanation button is selected,a ‘window appears that c&tains a text-based‘description or explanation of the sort algoritbm. The Algorithm button permits the selection of a sort algorithm. Presently there are six algorithms provided althoughmoie will be’addedin the nearfuture. A running display of the number of comparisonsand swaps is shownat the bottom of the window. The codefor the algorithm is in the right frame. The lines of code are highlighted as they are executedby the animation. The code currently provided with the Sort Animator is in Java, although this neednot be the case.Codein any languagecould be usedto expressthe algorithms, including pseudo-code. 3. Animation of Recursion A useful feature of the Sort Animator is its manner of displaying recursive sort algorithms. A collection of horizontal bars is addedat the top of the left frame to indicate the level of recursion andthe part of the sort list that is sortedby each recursivecall. The vertical position of the bar in usedto indi- This technique for illustrating recursion has the added advantagethat it provides a history of the sort as well. Figure 3 shows the completion of the sort that was in progressin Figure 2. The horizontal barsreflect the history of the quicksort with the partitions at each level clearly identified. The pivot element at eachlevel is also identified by the position of the spacebetweenthe bars. cate the level of recursion with the top bar drawn when the initial call is made, a bar underneaththe first bar at the second level drawn when the first recursive call is made, and each succeedingcall resulting in a bar drawn one level further down. The horizontal extent of each bar will exactly cover the portion of the sort list that is assignedto the correspondingrecursivecall. 4. Sort Animation Builder The Sort Animation Builder uses the Iame animation environmentas the Animator. The sort algorithm is provided by the user along with special instructions to direct the animation. To illustrate the simplicity of building an animation, an exampleis shown in Figure 4. This is the code that the user would provide for a simple recursive selection sort with the animation control statementsaccompaniedby explanatory comments. importjava.awt.*: class UserThread extends static int level - 0: public 1 UserlhreadCSortClass int findalnClnt ainloc int i: for Figure 2. Quicksort animation in progress , first. - first: (i-flrst+l: ifa:~;r;ty(ainloc.i)) -: 1 return f teep) supdtenp): int f SortThread Int I<-last: f last) f I+*1 // greater conpares elements at rlnloc and 1 einlcc: 1 Figure 2 showsa quicksort animationin progress.Eachhorizontal bar at the top of the left frame representsa recursive ,call that,has%been made.The top b,T is the original sort call on the entire list. The two shorterbars at the secondlevel are the two recursive calls madefrom the first activation of proceduresort. ‘The ieft of those tie is darker indicating it has alreadybeencompleted.At the third level, the two darkened barsto the left indicate that thosehavebeencompletedwhile the lighter colored bar on the right, is the sort range that is currently active. The remaining bars at levels four and five indicate furthk{complete$ sort calls: In Figures2,6 calls have beencompletedand 3 are still active. At any time, the lowest lighter-colored bar representsthe rangeof the active sort. void sortcint first. int last1 drarBar(first.last.O.sorter.sra skipStatenents(O.1): if Clewfirst) f int seal1 - findnin(first.last): ~setColorAt(seall.sorter.srapcolor~: dehIghlightW: f I/ color): highlights N /I // // N // I/ // i skipStateasntsC4.4): I/ If Sets tolor of alseent at small highlights statewnt 2 ulth de highlights statement 3 rithlda resets highllght on stateeont swaps eleaents first and seal1 colors first eleeont sortod dehi hl,ights statoront 3 hijhgights stateeont 4 with de / draws hor bar from first t last at depth o with backs N,dravs hor bar from firs first at deoth 0 rl th sortod c I/ colors // first drarBarCflrst.lest.0.sorter.backcolor): drarBar(first.first,O,sorter.sortedc~~or~: sortCfirst+l.lest): , 3 &se f 'rarWortedCfirst1: drar~arCfirst.first.O.sorter.sorfedcolor~~ ~kipStateeents(S.6): // draws horizontal bar statements o and 1 with delay highlights // first element draws hor bar at depth 0 rith statoeonts sorted from firs sorted c 5 and 6 with de 1 public void mealnO sortC0, getSizeO-1): 1I 3 f I Figure 4. Sort Animaior Code for Selection Sort To build a sort, the user provides a runmain ( ) function in the UserThread class.This classinherits all of the animation functions from its parent class, SortThread. The functions setColorAt, color, greater, and swap control the animation of the, data elements, the function drawBar controls the horizontal bars that illustrate recursion,and the functions skipStatements,highlight, and dehighlight control thecodeanimation. Otherfunctions are availablebeyondthoseusedin this illustration. Figure 5 shows a mid-sort window generatedby the code in 224 Figure 4. The code used for the code animation in the right frame is provided by the userin a separatefile. the sort algorithm, can stepthrough its execution, describing the role of eachpertinent step and addressingstudent questions. The Sort Animation Builder permits the instructor to implement algorithms or code from the textbook or algorithms of the instructor’s own choosing. 5. Conclusions The Sort Animator and Sort Animation Builder provide a number of significant benefitsto studentslearning sort algorithms and to their teachersas well. These tools are Java applets that can be run over the World Wide Web, making them accessibleto students in a variety of settings. This includes the closed laboratory, the open laboratory, and on their own computersystems. The animation of the algorithm’s code along with its visual animation gives the studentan explanation of eachstep as it is being carried out. This enhancesthe understandingof both the codeand the algorithm aswell ashow they correspondto each other. The Sort Animation Builder permits the teacher and the studentto implement code and algorithm animations themselves Thesetools can be usedin a variety of ways in courseswhere sort algorithms are discussed.First, they are valuable for classroomdemonstrations.The instructor, while describing 225 A,seconduseof thesetools is in studentlaboratory exercises. In such exercises,studentscan be askedto do comparative, empirical analysis of algorithms, aided by the Sort Animator’s view of the count of key operations.Also, since the animations arerun asJavathreads,it is possiblefor the students to conduct sort races to observe the relative efficiency of so@. Another tool sometimesusedin labs is to have the students observethe sort animation without the accompanying code, and identify from the animation the sort algorithm under observationfrom among,thosestudied in class. It is also possible, within a lab setting, to have studentsobserve the different behavior of the sort algorithms when the sort list is in order beforethe sort algorithm begins. A.final useof thesetools is to havestudentsdesigntheir own animations...This approach has been recommendedas an effectivelearning tool by Stasko[9], and the Sort Animation Builder gives the student a natural, easy-to-learn way to implement such animations. As students debug their algorithm and code, they will find the algorithm/codeanimation helpful in this processas it provides two of the three visualization approachesexplored by Baeckeret al[ lo]. The tools described here are available through a web site developedby the secondauthor.This site containslinks to an extensive collection of web-basedanimations of many different algorithms, including sort algorithms. It also contains a link to the Sort Animator and the Sort Animation Builder. The web site is located at www.cs.hope.edu/-alganim/ccaa/ccaa.html [9 Stasko,J.T. Using Student-Build Algorithm Animations asLearning Aids. Proceedings of the ZJventy-eighth SIGCSE Technical Symposium on Computer Science Education (SIGCSE Bulletin), 29, 1 (Mar. 1997),25-29. [lo] Baecker, R., DiGiano, C., and Marcus, A. Software Visualization for Debugging, Communications of the ACM 40,4 (Apr. 1997),44-54. Acknowledgments The authors would like to thank JamesVanderhyde,who contributedmany helpful ideasto this project. This work was partially funded by the National ScienceFoundation, Grant Number CDA-9423943-03. References [l] Baecker, R.M. Sorting out Sorting, color/sound film, University of Toronto, 1981. Distributed by Morgan Kaufmann, SanFrancisco1 [2] Naps,T.L. Algorithm Visualization in ComputerScience Laboratories,Proceedings of the Twenty-first SIGCSE Technical Symposium on Computer Science Education (SIGCSE Bulletin), 22, 1 (Feb. 1990), 105110. (31 Stasko,J.T.‘Tango: A framework.and‘system’for algorithm animation.IEEE’Computer, 23;9 (S&k 1990),+39-44. ” : : ‘i! [4] Brown, ‘M.H. Exploring algorithms using BALSA-II. IEEE Computer, 21,5 (May 1988), 1436. ’ [SJNaps, T.L. ,Algoritl@ visualization servedoff the World Wide Web:’ wlijr and how. Praceedings SIGCSE/SIGCUE ‘96, Barcelona,Spain 66-71. ’ .( (June 1996),pp. >,i..’ ’ Ii ’ [6] Brown, M:H!’ and Najork, MA. Collaborative,Active Textbooks: A Web~BasedAlgoiithm’ Animation Systemfor an Electronic Classroom.‘Digital Systems’Research Center Research Report 142, 1996. ;: ‘!I? ,1 /et %. ,. [7]‘Ungar’DY, Lieberman, H.‘and Fry; C.‘Dkbugging and the Experienceof 1mmedkcy:Communicatians 'of the ACM 40, .-. 9. 4 (Apr. 1997),38-43. ‘, [8] Dershem,H.L., Barth, W.L., Bowsher,C.J., and Brown, D.P: Data St&&ures with Ada Packages,Laboratories, and Animations. Praceedings of the ‘First Australasian Confere&e on Computer Science Education, Sydney, Australia, , (June1996),pp: 3’2-38. ” ’ ’ . 226 .s i