DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER - 1 INTRODUCTION 1.1 Overview of Computer Graphics Computer Graphics is concerned with all aspects of producing pictures or images using computer. These are intentionally fashioned to achieve some visual effects. Computer Graphics also refers to the tools used to make such pictures. There are both hardware and software tools. Hardware tools include video monitors and printers that display graphics, and input devices like a mouse or track ball. Software tools are editors, compilers, debugger found in any programming environment. Interactive computer graphics is the most important means of producing pictures since the invention of photography and television. A picture is worth ten thousand words. Interactive computer graphics thus permits extensive, high-bandwidth user-computer interaction. Computer graphics concerns with the pictorial synthesis of real or imaginary objects from their computer based models, where as the related field of image processing treats the converse process, the analysis of scenes, or the reconstruction of models of 2D or 3D objects from their pictures. Computer Graphics has become a powerful tool for the rapid and economical production of pictures. There is virtually no area in which Graphical displays cannot be used to some advantage so it is not surprising to find the use of Computer Graphics so widespread. 1.2 History of Computer Graphics This field began humbly almost 50 years ago, with display of a few lines on a cathode ray tube. William fetter was credited with coining the term Computer Graphics in 1960, to describe his work at Boeing. One of the first displays of computer animation was future world (1976), which included an animation of a human face and hand-produced by Carmull and Fred Parkle at the University of Utah. There are several international conferences and journals where the most significant results in computer-graphics are published. Among them are the SIGGRAPH and Euro graphics conferences and the association for computing machinery (ACM) transaction on Graphics journals. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 1 DYNAMIC SORTING ALGORITHM VISUALIZER 1.3 Application of Computer Graphics The applications of computer graphics are many and varied; however, we can divide them into four major areas as described: 1.3.1 Display of information Classical graphics techniques arose as a medium to convey information among people. Although spoken and written languages serve a similar purpose, the human visual system is unrivaled both as a processor of data and as a pattern recognizer. Today, architects, mechanical designers, generate the same type of information and drafts people-using computer based drafting systems. For centuries, cartographers have developed maps to display celestial and geographical information, which were crucial for navigators. Now, maps can be developed and manipulated in real time over internet. Medical imaging poses interesting and important data analysis problems. Modern imaging technologies such as computed tomography (CT), magnetic resonance imaging (MRI), ultrasound, and positron emission tomography (PET) generate threedimensional data that must be subjected t algorithmic manipulation to provide useful information. Supercomputers now allow researchers in many areas to solve previously intractable problems. In fields such as fluid flow, molecular biology, and mathematics, images generated by conversion of data to geometric entities that can be displayed have yielded new insights into complex processes. 1.3.2 Design Professions such as engineering and architecture are concerned with design. Starting with a set of specifications, engineers and architects seek a cost effective and esthetic solution that satisfies the specifications. Design is an iterative process. Design problems are either over determined, such that they posses no solution that satisfies all criteria, much less an optimal solution, or underdetermined, such that they have multiple solutions that satisfy the design criteria. Thus, the designer works iteratively by generating a possible design, testing it, and then using the results as the basis for exploring other solutions. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 2 DYNAMIC SORTING ALGORITHM VISUALIZER The use of interactive graphical tools in computer aided design (CAD) pervades fields including as architectures, mechanical engineering, the design of very-large scale integrated (VLSI) circuits, and the creation of characters for animations. In all these applications, the graphics are used in a number of distinct ways. 1.3.3 Simulation and Animation In real time, graphics systems are used as simulators. One of the most important uses has been in the training of pilots. Graphical flight simulators have proved to increase safety and to reduce training expenses. Games and educational software for home computers are almost as impressive. The simulator can be used for designing the robot, planning its path, and simulating its behavior in complex environments. Computer graphics is being widely used for animation in the television, motion picture, and advertising industries. Computers at a cost less than that of movies made with traditional hand-animation techniques can now make entire animated movies. The field of virtual reality (VR) has opened many new horizons. A human viewer can be equipped with a display headset that allows him to see separate images with his right and left eye, which gives the effect of stereoscopic vision. 1.3.4 User interface Our interaction with computers has become dominated by a visual paradigm that includes windows, icons, menus, and a pointing device, such as mouse. From a user’s perspective, windowing systems such as X Window System, Microsoft Windows, and the Macintosh OS X differ only in details. More recently, millions of people have become Internet users. Their access is through graphical network browsers, such as Firefox and Internet Explorer that use these same interface tools. We are so accustomed to this style of interface that we often forget that we are working with computer graphics. Now a days even school children are comfortable with interactive graphics techniques, such as the desktop metaphor for window manipulation and menu and icons selection with mouse. Graphics based user interfaces have made productive users of neophytes, and the desk without its graphics computer is increasingly rare. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 3 DYNAMIC SORTING ALGORITHM VISUALIZER 1.4 Statement of the Project Our statement of the project is “DEMONSTRATION OF DYNAMIC SORTING ALGORITHM VISUALIZER”. The concerning work is achieved by using computer graphics and its standard functions defined in OpenGL package using CodeBlocks IDE. 1.5 Objective of the Project To demonstrate the working of Dynamic Sorting Algorithm Visualizer using OpenGL. The main mode of input or interaction with the user is through the keyboard. 1.6 Organization of the Report Chapter 1 introduces the computer graphics and its applications. Chapter 2 contains the basic concepts and principles involved in OpenGL. Chapter 3 deals with Basic Concepts of the Dynamic Sorting Algorithm Visualizer. Chapter 4 deals with design and implementation of the Dynamic Sorting Algorithm Visualizer. Chapter 5 contains the snapshots and the result regarding project. Chapter 6 concludes the project and mentions the future scope. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 4 DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER - 2 REQUIREMENT SPECIFICATION INTRODUCTION TO OPENGL 2.1 Introduction OpenGL (Open Graphics Library)is a standard specification defining a crosslanguage, cross-platform API for writing applications that produce 2D and 3D computer graphics. OpenGL is not a programming language it is an API (Application Programming Interface). The interface consists of many different function calls which can be used for building application programs. OpenGL is widely used in CAD, virtual reality, scientific visualization, information visualization, and flight simulation. OpenGL is portable to many platforms (windows, MAC, UNIX, LINUX) and callable from many programming languages (C/C++, JAVA, PEARL). OpenGL is primarily concerned with modeling and rendering operations such as, to specify geometric primitives (lines, pixels, polygons…), apply geometric transformations and specify camera light, color, texture information etc. Figure2.1 Displaying Compatibility of OpenGL in other Platforms All functions in OpenGL library are device independent, many operations (windowing, I/O etc) are not included in basic core library, so different auxiliary libraries are developed for features not available in OpenGL. OpenGL libraries are OpenGL: GL (lib GL) and GLU (lib GLU) These are windows native implementation (OpenGL32) and Mesa3D: DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 5 DYNAMIC SORTING ALGORITHM VISUALIZER free ware implementation for LINUX. GLUT: OpenGL utility tool kit (lib glut) the GLUT library is responsible for window and menu management, mouse and keyboard interactions. Graphics libraries are GLUI: GLUT based user interface library (lib glut) -It controls OpenGL applications such as buttons, check boxes, radio buttons etc. Most of our application will be designed to access OpenGL directly through functions in three libraries. Functions in the main GL (or OpenGL in windows) library have names that begin with the letters gl and are stored in a library usually referred to as GL (or OpenGL in windows). The second is the OpenGL Utility Library (GLU). This library uses only GL functions but contains code for creating common objects and simplifying viewing. All functions in GLU can be created from the core GL library but application programmers prefer not to write the code repeatedly. The GLU library is available in all OpenGL implementations; functions in the GLU library begin with letters glu. To interface with the window system and to get input from external devices into our programs, we need at least one more library. For each major window system there is a system-specific library that provides the “glue” between the window system and OpenGL. For the X window system, this library is called GLX, for windows, it is wgl, and for the Macintosh, it is agl. Rather than using a different library for each system, we use a readily available library called the OpenGL Utility Toolkit (GLUT), which provides the minimum functionality that should be expected in any modern windowing system. GLU OpenGL Frame GL Buffer applicatio Xlib, n Program GLUT Xtk GLX Figure 2.2: Library organization Figure 2.2 shows the organization of the libraries for an X Window System environment. For this window system, GLUT will use GLX and the X libraries. The DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 6 DYNAMIC SORTING ALGORITHM VISUALIZER application program, however, can use only GLUT functions and thus can be recompiled with the GLUT library for other window systems. OpenGL makes heavy use of macros to increase code readability and avoid the use of magic numbers. Thus strings such as GL_FILL and GL_POIINTS are defined in header files. In most implementations, one of the include lines #include<GL/glut.h> Or #include<GLUT/glut.h> is sufficient to read in glut.h, gl.h, and glu.h. 2.2 Why OpenGL The intention of this chapter is to give you basic concepts in OpenGL. OpenGL is a device and operating system independent library for 3D-graphics and rendering. OpenGL was originally developed by Silicon Graphics Inc (SGI) for use on their high end graphics workstations. Since then, OpenGL has become a widely accepted standard with implementations on many operating system and hardware platforms including Windows NT and Windows X operating systems. The purpose of the OpenGL library is to render two and three-dimensional objects into frame buffer. OpenGL is a library of high-quality threedimensional graphics and rendering functions. The library's device- and platformindependence make it a library of choice for developing portable graphical applications. OpenGL drawings are constructed from primitives; primitives are simple items such as lines or polygons, which in turn are composed of vertices. The OpenGL Library assembles primitives from vertices while taking into account a variety of settings, such as color, lighting, and texture. Primitives are then processed in accordance with transformations, clipping settings, and other parameters; at the end of the rasterization, process is pixel data deposited into a frame buffer. Because of high visual quality and performance, any visual computing application requiring maximum performance-from 3D animation to CAD to visual simulation-can exploit high-quality, high-performance OpenGL capabilities. These capabilities allow developers in diverse markets such as broadcasting, CAD/CAM/CAE, entertainment, medical imaging, and virtual reality to produce and display incredibly compelling 2D and 3D graphics. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 7 DYNAMIC SORTING ALGORITHM VISUALIZER 2.3 Advantages of Using OpenGL Industry standard: An independent consortium, the OpenGL Architecture Review Board, guides the OpenGL specification. With broad industry support, OpenGL is the only truly open, vendor-neutral, multiplatform graphics standard. Stable: OpenGL implementations have been available for more than seven years on a wide variety of platforms. Additions to the specification are well controlled, and proposed updates are announced in time for developers to adopt changes. Backward compatibility requirements ensure that existing applications do not become obsolete. Reliable and portable: All OpenGL applications produce consistent visual display results on any OpenGL API-compliant hardware, regardless of operating system or windowing system. Evolving: Because of its thorough and forward-looking design, OpenGL allows new hardware innovations to be accessible through the API via the OpenGL extension mechanism. In this way, innovations appear in the API in a timely fashion, letting application developers and hardware vendors incorporate new features into their normal product release cycles. 2.4 Hardware and Software Requirements 2.4.1. Hardware System Processor: Dual core from or AMD Processor Speed: 2.0 GHz or above RAM: 4GB or above Operating System: Windows 7/8/10 2.4.2. Software Microsoft Windows XP/Windows 7-Operating System CodeBlocks IDE Coding Language: C++ Tools used: CodeBlocks, OpenGL DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 8 DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER - 3 BASIC CONCEPTS OF DYNAMIC SORTING ALGORITHM VISUALIZER This chapter contains a brief description about Dynamic Sorting Algorithm Visualizer including its definition, its operations, and traversals. Later overview of Dynamic Sorting Algorithm Visualizer has been described. At last the chapter concludes with the applications and features of Dynamic Sorting Algorithm Visualizer. 3.1 Project Description Dynamic Sorting Algorithm Visualizer basically implements one of the best sorting algorithms, (i.e.) Bubble Sort. This Visualizer makes use of the fact that OpenGL provides the low-level rendering routines allowing the programmer a great deal of control and flexibility. DSAV also make use of the prominent library of OpenGL (i.e.) GLUT. DSAV is broadly classified into 3 major steps. They are: Initial Representation. Swapping Process. Final Rendering. 3.1.2 Initial Representation: In the initial representation phase, DSAV generates a random sequence of numbers, which marks the beginning of this phase. This random sequence of numbers will be the input to our sorting algorithm. Based on this input we draw the scaled circles using GL_TRIANGLE_FAN of OpenGL with suitable radius and place them on the main window for sorting. Each circle is separated from each other by a constant distance. 3.1.3 Swapping Process: The Basic step behind a sorting algorithm is to swap two key elements. Here in our case is to swap the circles. Key elements are the circles that are undergoing the swapping process in the current iteration. The basic step of algorithm is comparison, through which we get the key elements for swapping. Once the key circles are known, we note down the X- coordinate DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 9 DYNAMIC SORTING ALGORITHM VISUALIZER of both the circles. Also, we initialize a flag by setting it to TRUE (1). Swapping circles is achieved by the following process: Decrease the center of circle in right till its center is greater than left circle. Increase the center of circle in left till its center is less than the right circle. If the absolute difference between the destination circle center and the initially taken values is less than 0.3, then we can conclude that the circles are swapped. Then reinitialize the flag to FALSE (0), indicating that for the current iteration the swapping process is completed. Also, change the centers of the swapped circles. 3.1.4 Final Rendering: Once the all the iterations are completed, we get the sorted array of elements. Thus, DSA Visualizer depicts this phase by presenting the circles in the increasing order of radius. Then we provide the menu system to user, which compromises of Randomizing, Sorting and Quit states. Based on the input of user the respective actions are carried out. Randomize: To generate the new random sequence. Sort: To employ the bubble sort algorithm to the newly generated sequence. Quit: To quit from the DSAV. 3.2 Overview Dynamic programming is an effective algorithm design method. Sorting is believed to be an unusual area for dynamic programming. Our finding is contrary to this conventional belief. Though it appears that classical sorting algorithms were designed using bottom up design approach, but we have found the evidence which suggests that some classical sorting algorithms can also be designed using Dynamic programming design method. Even the development of classical Merge algorithm shows elements of dynamic programming. This paper finds that development of sorting algorithms can be looked from an entirely different point of view. This work will reveal some new facts about the design or development of some key sorting algorithms. It was discovered that this new interpretation gives a deep insight about the design of some fundamental sorting algorithms. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 10 DYNAMIC SORTING ALGORITHM VISUALIZER 3.3 Working The underlying concept of sorting algorithm includes the comparisons, swapping of elements, and assignments. The DSAV (Dynamic Sorting Algorithm Visualizer), Visualizes the Bubble Sort Algorithm. In this algorithm, comparisons start from the first two elements of the array and finding the largest item and move (or bubble) it to the top. With each subsequent iteration, find the next largest item and bubble it up towards the top of the array. This DSA Visualizer depicts the swapping of elements by swapping the circles (which are the items of the array in our case), for each item different radii of circle are generated according to the value of the item. This swapping process occurs for at the max of n iterations. Thus, at the end of nth iteration, the array of elements is sorted in the ascending order which is the desired output of the DSAV. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 11 DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER - 4 DESIGN AND IMPLEMENTATION 4.1 Flowchart Figure 4.1 : Flowchart DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 12 DYNAMIC SORTING ALGORITHM VISUALIZER 4.2 PROCEDURE Step 1 : First the window generate will ask 'press enter to continue…' ; press enter key Menu is written with what to do on the screen itself. Step 2 : Following is what keyboard will do after it get pressed Step 3 : s : To start sorting r: To randomizes the sorted list Esc: Exit Step 4 : If we press ‘S’ the elements start sorting from acending to decending order. Step 5 : Then if we press ‘R’ the elements again arranged in a random way. Step 6 : Later if we select ‘ESC’ the demo window gets closed. 4.3 IMPLEMENTATION GL FUNCTIONS glBegin(GL_LINES); Treats each pair of vertices as an independent line segment.Vertices 2 n-1 and 2 n define line n.N 2 lines are drawn. glBegin(GL_LINE_LOOP); Draws a connected group of line segments from the first vertex to the last.Vertices n and n+1 defines line n.N-1 lines are drawn. glutCreateWindow Creates a top-level window. glutDisplayFunc Sets the display callback for the current window. glutInit Initialize the Glut library and negotiates session with the window system. glutInitDisplayMode The initial display mode is used when creating top-level windows, sub windows, and overlays to determine the OpenGL display mode for the to be created window or overlay. glutInitWindowPosition DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 13 DYNAMIC SORTING ALGORITHM VISUALIZER Sets the initial window position. glutInitWindowSize Sets the initial window size. glutKeyboardFunc Sets the keyboard callback for the current window. glutPostReDisplay(); Marks the normal plane of current window as needing to be redisplay. glFlush(); Forces any buffer OpenGL commands to execute. glutMainLoop() ; Cause the program to enter an event-processing loop. It should be the last statement in main. Defines an orthographic viewing volume with all parameters measured from the centre of the projection plane. glViewport Specifies a width*height viewport in pixels whose lower-left corner is at measured from the origin of the window. glClearColor(GLclampf r, GLclampf g, GLclampf b, GLclampf a); Sets the present RGBA clear color used when clearing the color buffer. Variables of GLclampf are floating-point numbers between 0.0 and 1.0. gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top); Defines a two dimensional viewing rectangle in the plane z=0. glRasterPos(); Specifies the raster position. The parameters are same as for glVertex. glutBitMapCharacter(void * font, int char); Renders the character with the ASCII code at the current raster position using the raster font given by font. Fonts include GLUT_BITMAP_TIMES_ROMAN_10 and GLUT_BITMAP_TIMES_ROMAN_8_BY_13. The raster position is incremented by the width of the character. glEnd(); Terminates the list of vertices. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 14 DYNAMIC SORTING ALGORITHM VISUALIZER glColor3f(); sets the present RGB colors. valid type is float. The maximum and minimum values of values of the discrete types are those of the type, for example 255 and 0 for unsigned bytes. glVertex(); specifies the posiyion of vertex in 2,3 or 4 dimensions .The coordinates can be specified as shorts s, ints i, floats f or doubles d. If the v is present , the argument is a pointer to an array containing the coordinates. glPushMatrix(); and glPopMtrix(); The glPushMatrix and glPopMatrix functions push and pop the current matrix stack. glTranslatef(); The glTranslated and glTranslatef functions multiply the current matrix by a translation matrix. SYNTAX: void glTranslate( x, y, z); PARAMETERS: x, y, z - The x, y, and z coordinates of a translation vector. glRasterPos2i(); Specifies the raster position for pixel operation. DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 15 DYNAMIC SORTING ALGORITHM VISUALIZER 4.4 ALGORITHM Step 1: Start Dynamic Sort Step 2: input a List Step 3: sorted = False Step 5: integer swaps = 0 Step 6: for I =1 to list. Count - 1 Step 7: if list [i-1]>list[i] go to step number 8 else to step 6 Initialize temp=list [i-1] List [i-1] = list[i] List[i] = temp Step 8: swaps = swaps + 1 Step 9: if swaps == 0 go to step 15 else go to step 16 Step 10: Update variable sorted with Boolean value “True” Step 11: Variable Sorted = False Step 12: Output List Step 13: End Dynamic Sort DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 16 DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER – 5 RESULTS AND SNAPSHOTS Figure 5.1: Welcome Window Figure 5.2: Main Window DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 17 DYNAMIC SORTING ALGORITHM VISUALIZER Figure 5.3: Sorting Elements Figure 5.4 Sorted Elements DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 18 DYNAMIC SORTING ALGORITHM VISUALIZER Figure 5.5: Randomized Elements DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 19 DYNAMIC SORTING ALGORITHM VISUALIZER CHAPTER – 6 CONCLUSION AND FUTURE SCOPE 6.1 Conclusion The concept and implementation of Dynamic Sorting Algorithm Visualizer is very easy to visualize, hence this project aimed at implementing and sorting of elements with the use of OpenGL. This Algorithm is well understood with the graphical and animation approach. The demo is made more interactive with the use of keyboard interaction module in the program. This project helped us a lot to learn about the proper utilization of various OpenGL graphics library functions that are defined in main GL (or OpenGL in windows), GLU (OpenGL Utility Library) and GLUT (OpenGL Utility Toolkit). DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 20 DYNAMIC SORTING ALGORITHM VISUALIZER BIBLIOGRAPHY Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. Introduction to Algorithms, Second Edition. MIT Press and McGraw-Hill, 2001. Anagnostopoulos, R. Kumar, M. Mahdian, E. Upfal, F. Vandin, Algorithms on dynamic graphs. Manuscript, 2010. T.H. Cormen, C.E. Leiserson, R.L. Rivest, C. Stein, Introduction to Algorithms, MIT Press, 2001. S. Muthukrishnan, Data Streams: Algorithms and Applications, Now Publishers Inc., 2005. Fundamentals of Data Structures by Ellis Horowitz, Sartaj Sahni and Susan Anderson-Freed ISBN 81-7371-605-6. Websites 1. www.opengl.org 2. www.sourcecode.com 3. www.google.com 4. www.wikipedia.orgs DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING, BCE, SHRAVANABELAGOLA 21