Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 20

DYNAMIC SORTING ALGORITHM VISUALIZER

 
VISVESVARAYA TECHNOLOGICAL UNIVERSITY
Jnana Sangama, Belgaum-590014, Karnataka, INDIA
 

 
Project Report
On
 
“DYNAMIC SORTING ALGORITHM VISUALIZER”
 
 
Submitted in partial fulfillment of the requirements for the VI Semester
 
Bachelor of Engineering
IN
COMPUTER SCIENCE AND ENGINEERING
 
For the Academic year
2008-2009
 
BY
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
LOGO of College
 
 
DYNAMIC SORTING ALGORITHM VISUALIZER

 
LOGO of College
 
 

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

      This is to certify that the project entitled “DYNAMIC


SORTING ALGORITHM VISUALIZER” is a bonafide work
carried out by NAME bearing register number USN in partial fulfillment for
the award of Degree of Bachelors (Bachelors of Engineering) in Computer
Science and Engineering of Visvesvaraya Technological University, Belgaum
during the year 2008-2009.
 

Signatures:

Seminar Guide           Head of the Dept

             Mr. Teacher


Head of the department
COMPUTER SCIENCE
ENGINEERING

ABSTRACT
 
 
Sorting problems is to rearrange the items of the given list in Ascending Order.
The underlying concept of sorting algorithm includes the comparisons, swapping of
elements, and assignments.
 
DYNAMIC SORTING ALGORITHM VISUALIZER

 
In DSAV ( Dynamic Sorting Algorithm Visualizer ), we are Visualizing the Bubble Sort
Algorithm.
 
 
In this algorithm, comparisons starts 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. Our DSA Visualizer depicts
the swapping of elements by swapping the circles (which are the items of the array in our
case). This swapping process occurs for at the max of n iterations.
 
 
Thus at the end of nth iteration, we can conclude that the array of elements are sorted in
the ascending order which is the desired output of the DSAV.
 
 
 
 
 
 
 
 
 

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

ACKNOWLEDGEMENT 
 
DYNAMIC SORTING ALGORITHM VISUALIZER

      Behind every success there is a master hand. A master hand will create unperturbed
concentration, dedication and encouragement in everything good and bad, without whose
blessing this would have never come into existence. 

      I thank , Principal/Director, PESSE for not only providing us with excellent
facilities, but also for offering his unending encouragement that has made this project a
success today. 

      Esteemed gratitude is due to , HOD of Computer Science & Engineering for his
valued co-operation in completion of this report. 

      I am also extremely grateful to my seminar guide & coordinator, Ms xxxxx for her
constant support and advice throughout the course of preparation of this document. 

      I would also like to extend my sincere gratitude to the faculty and non-teaching staff of
the department of CSE for extending their technical suggestion and being a constant
source of inspiration behind this seminar. 

      Finally, I would like to thank all friends and well-wishers who helped me with the
content of this report, without which the seminar would not have become a reality. 
 
 

      
 
         Signature
 
 
 
 
 
 
 
 
CONTENTS
 
 
 
 
1. Introduction to OpenGL
2. Project description
3. API’s
DYNAMIC SORTING ALGORITHM VISUALIZER

4. Implementation Details
5. Source code
6. Sample outputs
7. Conclusion
8. Bibliography
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1. INTRODUCTION TO OpenGL
OpenGL was originally developed by Silicon Graphics, Inc. (SGI) as a multi-
purpose, platform-independent graphics API. Since 1992, the development of OpenGL has
been overseen by the OpenGL Architecture Review Board (ARB), which is made up of
major graphics vendors and other industry leaders, currently consisting of 3DLabs, ATI,
Dell, Evans & Sutherland, Hewlett-Packard, IBM, Intel, Matrox, NVIDIA, SGI, Sun
Microsystems, and Silicon Graphics. The Role of ARB is to establish and maintain the
DYNAMIC SORTING ALGORITHM VISUALIZER

OpenGL specifications, which dictates which features must be included when one is
developing an OpenGL distribution. OpenGl is the premier environment for developing
portable, interactive 2D and 3D graphics applications.

OpenGL intentionally provides only low-level rendering routines, allowing the


programmer a great deal of control and flexibility. The provided routines can easily be
used to build high-level rendering and modeling libraries, and in fact, the OpenGL Utility
Library(GLU), which is included in most OpenGL distributions, does exactly that. Note
that OpenGL is just a graphics library ; Unlike DirectX, it does not include support for
sound, input, networking, or anything else not directly related to graphics.
 
OpenGL is a collection of several hundred functions providing access to all of the
features offered by our graphics hardware. Internally, it acts as a state machine – a
collection of states that tell OpenGL what to do and that are changed in a very well-
defined manner. Using API, we can set various aspects of the state machine, including
such things as the current color, lighting, blending et al. When rendering, everything
drawn is affected by the current settings of the state machine. At the core of OpenGL is
the rendering pipeline.
 
There are many libraries available that build upon and around OpenGL to add
support and functionality beyond the low-level rendering support that it excels at. Most
important amongst them are GLU, GLUT and SDL.GLU uses only GL functions but
contains code for creating common objects and simplifying viewing. GLUT provides
support for any form of functionality related to windowing, menus or input. SDL stands
for Simple Direct Media Layer is a cross-platform multimedia library, including support
for audio, input, 2D graphics.

2. PROJECT DESCRIPTION
 
Dynamic Sorting Algorithm Visualizer basically implements one of the best
sorting algorithm, (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.
DYNAMIC SORTING ALGORITHM VISUALIZER

 Final Rendering.

 
2.1 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.
 
2.2 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 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 centre of circle in right till its center is greater than left circle.
 Increase the centre of circle in left till its center is less than the right circle.

If the absolute difference between the destination circle centre 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.
 
2.3 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. APIs Used
 
3.1 void glutInit(int *argcp, char **argv);
glutInit is used to initialize the GLUT library. argcp a pointer to the program’s
unmodified argc variable from main. Upon return, the value pointed to by argcp will be
updated, because glutInit extracts any command line options intended for the GLUT
library. argv the program’s unmodified argv variable from main and like argcp, the data
DYNAMIC SORTING ALGORITHM VISUALIZER

for argv will be updated if we pass any command line options, that GLUT library
understands.
 
 
 
3.2 void glutInitDisplayMode(unsigned int mode);
Sets the initial display mode. Display mode, normally the bitwise OR-ing of GLUT
display mode bit masks. The Bit mask values are :
GLUT_SINGLE   : Bit mask to select a single buffered window.
GLUT_DOUBLE : Bit mask to select a double buffered window. This overrides
GLUT_SINGLE if it is also specified.
GLUT_RGBA : Bit mask to select an RGB mode window. This is the default if neither
GLUT_RGBA nor GLUT_INDEX are specified.
 
3.3 void glutInitWindowSize(int width, int height);
Specifies the initial height and width of the window in pixels.
 
3.4 void glutInitWindowPosition(int x, int y)
Specifies the initial position of the top-left corner of the window in pixels.
 
3.5 int glutCreateWindow(char * name)
glutCreateWindow creates a top-level window. The name will be provided to the
window system as the window’s name. The intent is that the window system will label the
window with the name.
 
 
 
 
3.6 void glutDisplayFunc(void ( * func ) ( void ) )
This sets the display callback for the current window. When GLUT determines that
the normal plane for the window needs to be redisplayed, the display callback for the
window is called.
 
3.7 void glutReshapeFunc(void * func ( int width, int height))
DYNAMIC SORTING ALGORITHM VISUALIZER

glutReshapeFunc sets the reshape callback for the current window. The reshape
callback is triggered when a window is reshaped. The width and height parameters of the
callback specify the new window size in pixels.
 
3.8 void glutMouseFunc(void *func ( int button, int state, int x, int y ) )
glutMouseFunc sets the mouse callback for the current window. When a user
presses and releases mouse buttons in the window, each press and each release generates a
mouse callback. The button parameter is one of GLUT LEFT BUTTON ,GLUT MIDDLE
BUTTON or GLUT RIGHT BUTTON. The state parameter is either GLUT UP or GLUT
DOWN indicating whether the callback was due to a release or press respectively. The x
and y callback parameters indicate the window relative coordinates when the mouse
button state changed. Passing NULL to glutMouseFunc disables the generation of mouse
callbacks.
 
3.9 void glutKeyboardFunc(void *func ( char key, int width, int height ) )
glutKeyBoardFunc sets the keyboard callback for the current window. When a user
types into the window, each key press generating the ASCII character will generate a
keyboard callback. The key callback parameter is the generated ASCII character.
 
3.10 void glutMainLoop( void )
glutMainLoop enters the GLUT event processing loop. This routine should be
called at most once in a GLUT program and once called, this routine will never return. It
should be the last statement in main function.
 
 
 
 
 
3.11 void glutClearColor( GLclampf r, GLclampf g, GLclampf b, GLclampf a)
Specify the red, green, blue, and alpha values used when the color buffers are
cleared. The initial values are all 0. Values specified by glClearColor are clamped to the
range [0,1].
 
3.12 void glutPostRedisplay( void )
DYNAMIC SORTING ALGORITHM VISUALIZER

Mark the normal plane of current window as needing to be redisplayed. In the next
iteration to the glutMainLoop, the window’s display callback will be called to redisplay
the window’s normal plane.
 
3.13 void glColor3f( TYPE red , TYPE green , TYPE blue )
Sets the Red, Green and Blue colors. Here f indicates that the values passed are
floating-point numbers. Similarly we can have integer or double values specified as
arguments.
 
3.14 void glBegin( glEnum mode )
glBegin along with the glEnd delimit the vertices that define a primitive or a group
of like primitives. This function takes mode as the parameter .Values of mode are :
GL_POINTS, GL_LINES, GL_POLYGON, GL_TRIANGLE_FAN,
GL_LINE_LOOP,GL_QUADS.
 
3.15 void glEnd( void )
glEnd ends the collection of values for primitive defined using the mode parameter
in glBegin.
 
3.16 void glFlush()
glFlush forces the execution of GL commands in finite time.
 
3.17 void glutSwapBuffers( void )
glutSwapBuffers promotes the contents of the back buffer of the layer in use of the
current window to become the contents of the front buffer.
 
 
 
3.18 void gluOrtho2D(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top)
gluOrtho2D defines a 2D Orthographic Projection Matrix. Here left and right
parameters specify the coordinates from the left and right vertical clipping planes, bottom
and top parameters specify the horizontal clipping planes.
 
3.19 void glViewport(int x, int y, GLsizei width, GLsizei height)
DYNAMIC SORTING ALGORITHM VISUALIZER

Here x, y specify the lower left corner of the viewport rectangle, in pixels. The
initial value is (0,0). Width, height specify the width and height of the viewport.
glViewport specifies the affine transformation of x and y from normalized device
coordinates to window coordinates.
 
3.20 void glMatrixMode(GLenum mode)
This would specify which matrix is the target for subsequent matrix operations.
The values accepted for glMatrixMode are :
GL_MODELVIEW, GL_PROJECTION, GL_TEXTURE.
The default value is GL_MODELVIEW.
 
3.21 void LoadIdentity()
Replaces the current matrix with the identity matrix. It is semantically equivalent
to calling the glLoadMatrix subroutine with the following identity matrix :

 
3.22 void glEnable( GLenum cap )
It enables server-side GL capabilities. Cap specifies a symbolic constant indicating
a GL capability. The cap values are :
GL_DEPTH_TEST : If enabled, do depth comparisons and update the depth buffer.
GL_LIGHTING : If enabled, use the current lighting parameters to compute the vertex
color or index.
GL_LIGHTi : If enabled, include light I in the evaluation of lighting equation.
GL_NORMALIZE : If enabled, normal vectors specified with glNormal are scaled to unit
length after transformation.
 
3.23 void glBlendFunc(GLenum source, GLenum destination)
This specify pixel arithmetic. glBlendFunc specifies how the red, green, blue, and
alpha source blending factors are computed. Nine symbolic constants are accepted:
GL_ZERO,GL_ONE,GL_DST_COLOR,GL_ONE_MINUS_DST_COLOR,GL_SRC_AL
PHA,
DYNAMIC SORTING ALGORITHM VISUALIZER

GL_ONE_MINUS_SRC_ALPHA,GL_DST_ALPHA,AL_ONE_MINUS_DST_ALPHA,
AND GL_SRC_ALPHA_SATURATE. The initial value is GL_ONE.
 
3.24 glHint(GLenum target, GLenum mode)
Specify implementation-specific hints. Target specifies a symbolic constant
indicating the behaviour to be controlled. GL_FOG_HINT,GL_LINE_SMOOTH_HINT,
GL_PERSPECTIVE_CORRECTION_HINT are some of the accepted values.
 
3.25 glDisable( GLenum cap)
cap specifies a symbolic constant indicating a GL capability. This disables an
OpenGL capability specified by the glEnable function.
 
3.26 gluLookAt( GLdouble eyeX, GLdouble eyeY, GLdouble eyeZ, GLdouble centerX,
GLdouble centerY, GLdouble centerZ, GLdouble upX, GLdouble upY, GLdouble upZ);
gluLookAt creates a viewing matrix derived from an EYE point, a REFERENCE
POINT indicating the center of the scene, and an UP vector.
eyeX, eyeY, eyeZ specifies the position of the eye point.
centerX, centerY, centerZ specifies the position of the reference point.
upX, upY, upZ specifies the direction of the UP vector.
 
 
 
 
 
 
 
 
 
4. IMPLEMENTATION DETAILS
 
4.1 Operating System and Languages used :
·      Windows XP
·      Languages/Tools Used : OpenGL, C, C++, Object Oriented Concepts.
DYNAMIC SORTING ALGORITHM VISUALIZER

 
4.2 Data Structures :
A structure defining the circle, compromising of circle centre coordinates as well
as the radius. An array of circles used to hold the randomly generated sequence of circles
for sorting purpose. Two global variables which holds the values of X coordinate of the
key circles. Finally the flags used to indicate whether the swapping process is happening
or not.
 
4.3 Functions Used :
 
4.3.1 void initialise (void)
In this function the swapping flag along with global variables that hold values of X
coordinates during swapping are initialized to zero. It also initializes the array of circles
that is obtained from the randomly generated sequence and place them at equal intervals.
 
4.3.2 void bitmap_output(int x, int y, char *string, void *font)
This function is used to print the text on the visualizer window. It takes x and y as
pixel values, which is the point on the screen where the character is required to be printed
of type font. Positioning is achieved through glRasterPos2f(x,y). If string is needed to be
printed then, find the length of the string needed to be printed and using the loop construct
call glutBitmapCharacter to print the character by character until the loop ends.
 
4.3.3 void int_str( int rad,char r[] );
This function does the conversion of integer value to string value, so that it can be
passed as parameter to the bitmap output function. It takes rad as the parameter which is
the target number that needs conversion from integer to string value.
 
 
4.3.4 void circle_draw(circle c);
This function draws the circle as per the passed circle structure variable, which
consists of the circle center coordinates along with the radius. Here we use the OpenGL
functions such as glBegin(), glEnd(), glVertex2f() to draw the circle. Here we are drawing
the circle with the help of GL_TRIANGLE_FAN which is passed as parameter to glBegin.
DYNAMIC SORTING ALGORITHM VISUALIZER

Also we are representing the radius of the respective circle just below the circle.
 
4.3.5 void swap_circles(circle *cc1,circle *cc2)
This function basically swaps the two key circles. Initially the X coordinates of the
two circles are assigned to the 2 global variables and swapping flag is made TRUE.
As long as the first global variable is less than or equal to second circle X coordinate,
decrement the second circle X coordinate by 1 unit. Similarly increment the other circle X
coordinate by 1 unit till the second global variable value is greater than the second circle
to be swapped. Once the absolute difference between the global X1, circle2 X coordinate
and global X2 , circle1 X coordinate becomes less than 0.3. That’s where the circles are
swapped. Change the centers of the two circles and make flag swapping=0.
 
4.3.6 void sort()
This function basically does the sorting process.
Logic of this functions is:
If not in the process of swapping of 2 circles then only get 2 new circles to swap.
While the counter_i < 10
While counter_j <9
If the a[counter_j] > a[counter_j]
Swap 2 circles
Once exchanged goto swap
Increment counter_j
      Increment counter_i
Swap:
Print which circles are getting swapped.
Call swap_circles function again with counter_j and counter_j+1 values.
Mark the end of the function sort.
 
 
4.3.7 void display_text( void )
This function is going to display the text on the visualizer window based on the
sorting flag. If sorting =0 then the function displays the menu else if sorting = 1 then
display the appropriate message.
 
DYNAMIC SORTING ALGORITHM VISUALIZER

4.3.8 void display(void)


This function basically draws the circle. This function makes use of the OpenGL
functions such as glBegin(), glVertex2i(), glColor3f(), glPointSize(), glFlush(),
glutSwapBuffers() for the smooth rendering of the circles which are the key elements in
our sorting.
 
4.3.9 void main_menu(int value)
This function basically calls the display function based on the value passed as
argument and also based on sorting flag. If sorting flag = 1 then display is called else
initialize() function is called.
 
4.3.10 void keyboard (unsigned char key, int x, int y)
This function just checks whether the input character is s or r or 27. Based on the
input if it is 27, exit(0) function is called, else if it is ‘s’ then sorting flag is initialized to 1
else if ‘r’ then intialise() function is called.
 
4.3.11 void reshape(int w, int h)
This function is used to reshape the window with the new width and height which
is passed as parameters. This function is triggered whenever the current window is
reshaped. This functions uses the goOrtho() to reshape the window. This is done by first
switching to GL_PROJECTION mode then calling glOrtho() function, finally switching
back to GL_MODELVIEW.
 
4.3.12 void init(void)
This function uses three gl functions to initialize the current window (i.e)
glClearColor(), glMatrixMode(), gluOrtho2D() to set the window background color, and
to define the 2D orthographic projection matrix.
 
 
4.3.13 void main(int argc, char ** argv)
This is the function from where the execution of the program begins.
In this function we have certain “gl” functions used to initialize the basic glut window
with desired properties. After initialization the display function is called with respect to
DYNAMIC SORTING ALGORITHM VISUALIZER

the window and finally the last statement of this section is the glutMainLoop(). Which is
an event processing function that enters into an infinite loop.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5. SOURCE CODE :
 
 
 
DYNAMIC SORTING ALGORITHM VISUALIZER

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6. SAMPLE OUTPUT :
 
 
DYNAMIC SORTING ALGORITHM VISUALIZER

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7. Conclusions :

 
 
 
DYNAMIC SORTING ALGORITHM VISUALIZER

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8. Bibliography :
 
 
8.1 Text Books :
 
1. Interactive Computer Graphics
DYNAMIC SORTING ALGORITHM VISUALIZER

A Top-Down Approach Using OpenGL


- Edward Angel.

 
8.2 WebLinks :

1.      http://www.videotutorialsrock.com/
 
2.      http://www.youtube.com/
 
3.      http://nehe.gamedev.net/
 

You might also like