Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (1 vote)
368 views

Sorting Visualizer

The document describes a sorting visualizer tool created to help students learn sorting algorithms. It contains an introduction explaining the motivation for the tool and overviewing the popular sorting algorithms it covers - selection sort, bubble sort, insertion sort, and merge sort. It also describes the technologies used to build the sorting visualizer - HTML, CSS, and JavaScript. The tool animates how each algorithm modifies and organizes data in an interactive web-based format.

Uploaded by

Captain America
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
368 views

Sorting Visualizer

The document describes a sorting visualizer tool created to help students learn sorting algorithms. It contains an introduction explaining the motivation for the tool and overviewing the popular sorting algorithms it covers - selection sort, bubble sort, insertion sort, and merge sort. It also describes the technologies used to build the sorting visualizer - HTML, CSS, and JavaScript. The tool animates how each algorithm modifies and organizes data in an interactive web-based format.

Uploaded by

Captain America
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

SORTING VISUALISER

Project Report Submitted to

Chhattisgarh Swami Vivekanand Technical University, Bilaspur (India)

In partial fulfilment for award of the degree of


BACHELOR OF TECHNOLOGY In Computer Science and Engineering
By
Ms. Roshni Rathore
Ms. Nidhi Shiware
Ms. Kanishka Rai

Under the Guidance of

Mr. Nitesh Nema

Department of Computer Science and Engineering Lakhmi Chand


Institute of Technology, Bilaspur

Session 2021-22
AKNOWLWEDGEMENT

We would like to express my gratitude towards Mr. Nitesh Nema for guiding me throughout
the project. We also feel thankful and express my kind gratitude towards our principal for
allowing me to conduct the project named SORTING VISUALIZER. The mentioned project
was done under the supervision of Mr. Nitesh Nema & thanking all participants for their
positive support and guidance.

We feel thankful to the college staff for giving me such a big opportunity. We believe that we
will enrol in more such events in the coming future. Ensuring that this project was done by
us and is not copied.
INDEX

1. ABSTRACT

2. INTRODUCTION

3. DEFINITION OF SORTING VISUALIZER

4. POPULAR SORTING ALGORITHMS


4.1 SECTION SORT
4.2 BUBBLE SORT
4.3 MERGE SORT
4.4 INSERTION SORT
4.5 QUICK SORT
4.6 HEAP SORT
5. LANGUAGES USED IN BUILTING SORTING VISUALIZER
5.1 HTML
5.2 CSS
5.3 JAVASCRIPT
SORTING VISUALIZER

1. ABSTRACT

Algorithm analysis and design is a great challenge for both computer and information science
students. Fear of programming, lack of interest and the abstract nature of programming
concepts are main causes of the high dropout and failure rates in introductory programming
courses. With an aim to motivate and help students, a number of researchers have proposed
various tools.
Although it has been reported that some of these tools have a positive impact on acquiring
programming skills, the problem still remains essentially unresolved. This paper describes
sorting visualisation, a tool for visualization of sorting algorithms.
Sorting visualizer is an easy-to-set-up and fully automatic visualization system with step-by-
step explanations and comparison of sorting algorithms. Design principles and technical
structure of the visualization system as well as its practical implications and educational
benefits are presented and discussed.
2. Introduction

How do you work out a problem? The problem itself doesn’t need to be anything overly complex,
such as trying to replace a broken headlight in your car (although nowadays, manufacturers are
trying the patience of the community with their increasingly abstract, space-age designs). The point
is how to attack the problem. Do you perform research, such as looking through your car’s manual
for step-by-step instructions, or is your first instinct to find someone who knows how to do it
(whether they are right next to you or in an online video)? My instinct is the latter, as I am a visual
learner and am adept to picking up concepts by seeing it done, rather than reading about it. For
example, when I was learning about sorting algorithms while pursuing my Computer Science
degree, I found that seeing the data move to its correct position under the constraints of an
algorithm was much easier to follow than tracing the code by hand. That led to the inspiration of
this paper, which describes a web-based tool I created that animates how sorting algorithms modify
and organize a set of data. If you need to organize a list of people by their age in ascending order,
for example, there are multiple algorithms that can perform the task. I visualized four of the well-
known ones by representing numerical data as a histogram.1 Each number is illustrated as a bar and
has a different height based on its value. This would make it distinct from the rest of the data as it is
being shifted by the algorithm from its original, unordered position to its final ordered position. The
four algorithms are: Selection Sort, Bubble Sort, Insertion Sort, and Merge Sort.2 Keeping in line
with the example of sorting people by age, let’s pretend that you have printed the age of each
person on a separate index card. One way to go about organizing the cards is to first find the
smallest age in the pile and bring it to the front. Then, find the next smallest and place it behind the
already ordered first age. Eventually, you will end up with a pile of index cards that list the ages in
ascending order. This method is exactly how Selection Sort works, where to sort a set of data, you
select the smallest first, and then the next smallest and the next smallest. This algorithm is not very
difficult to understand by word of mouth, but more abstract sorting algorithms, such as how Quick
Sort requires moving data around a pivot point, may not be intuitive to read through. I wanted the
animation to be web-based to appeal to a wide spectrum of people using different technology
media. This way, the user would not need to worry about installing special software or trying to
organize configurations to use the tool. The webpage is coded with HTML5 (Hypertext Markup
Language, Version 5), JavaScript, and CSS (Cascading Style Sheets). The physical elements of the
webpage (buttons and layout) are coded with very minimal HTML5 code. The next biggest
contributor would be the CSS code, which is responsible for the appearance and behavior of the
buttons and text. Finally, the rest is devoted to JavaScript, responsible for the histogram generation,
movement, algorithm design, and sound. All the

buttons refer to designated parts of the JavaScript code to perform the task. I did have some
experience creating web pages from previous internships, but not nearly enough to handle this task
effectively. Most of the time, I was coding in a simple text editor and was hunting for syntactical
errors by hand. Toward the end of the project was when I found out that browsers have a built-in
developer tab that highlights syntactical errors. Before this, when my code broke, the histogram
would just disappear and I had no idea why. Chapter Two of this paper discusses work and
conclusions made by other similar studies, and also provides references to types of more recent
video animation. Chapter Three is a top-level view of how the animation works and how a user
would perform the sorts. Chapter Four is an in-depth view of the underlying structure of the code
and how it relates to the final animation. Chapter Five describes my methods and results of user
testing and Chapter Six concludes my findings with a tangent of how this would relate to future
work. All the code is in the appendix and can be made into a single HTML file, so if you want to
use it, go for it.
3. Definition of sorting visualizer
In computer science, a sorting algorithm is an algorithm that puts elements of a list into an order.
The most frequently used orders are numerical order and lexicographical order, and either ascending
or descending. Efficient sorting is important for optimizing the efficiency of other algorithms (such
as search and merge algorithms) that require input data to be in sorted lists. Sorting is also often
useful for canonicalizing data and for producing human-readable output.

Formally, the output of any sorting algorithm must satisfy two conditions:

1. The output is in monotonic order (each element is no smaller/larger than the previous


element, according to the required order).
2. The output is a permutation (a reordering, yet retaining all of the original elements) of
the input.

Classification
Sorting algorithms can be classified by:

 Computational complexity
o Best, worst and average case behaviour in terms of the size of the list. For typical
serial sorting algorithms, good behaviour is O(n log n), with parallel sort in O(log2 n),
and bad behaviour is O(n2). Ideal behaviour for a serial sort is O(n), but this is not
possible in the average case. Optimal parallel sorting is O (log n).
o Swaps for "in-place" algorithms.
o Memory usage (and use of other computer resources). In particular, some sorting
algorithms are "in-place". Strictly, an in-place sort needs only O(1) memory beyond
the items being sorted; sometimes O(log n) additional memory is considered "in-
place".
o Recursion: Some algorithms are either recursive or non-recursive, while others may
be both (e.g., merge sort).
o Stability: stable sorting algorithms maintain the relative order of records with equal
keys (i.e., values).
o Whether or not they are a comparison sort. A comparison sort examines the data only
by comparing two elements with a comparison operator.

4.Popular sorting algorithms

4.1 Selection Sort

The selection sort algorithm sorts an array by repeatedly finding the minimum element
(considering ascending order) from unsorted part and putting it at the beginning. The algorithm
maintains two subarrays in a given array.
1) The subarray which is already sorted. 
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the
unsorted subarray is picked and moved to the sorted subarray. 

Time Complexity: O(n2) as there are two nested loops.


Auxiliary Space: O(1) 
The good thing about selection sort is it never makes more than O(n) swaps and can be useful
when memory write is a costly operation. 
Following example explains the above steps:

arr[] = 64 25 12 22 11

// Find the minimum element in arr[0...4]

// and place it at beginning

11 25 12 22 64

// Find the minimum element in arr[1...4]


// and place it at beginning of arr[1...4]
11 12 25 22 64

// Find the minimum element in arr[2...4]


// and place it at beginning of arr[2...4]
11 12 22 25 64

// Find the minimum element in arr[3...4]


// and place it at beginning of arr[3...4]
11 12 22 25 64
Flow chart of selection sort
4.2 Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
Example: 
First Pass: 
( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5
> 1. 
( 1 5 4 2 8 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4 
( 1 4 5 2 8 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2 
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ), Now, since these elements are already in order (8 > 5), algorithm
does not swap them.
Second Pass: 
( 1 4 2 5 8 ) –> ( 1 4 2 5 8 ) 
( 1 4 2 5 8 ) –> ( 1 2 4 5 8 ), Swap since 4 > 2 
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
( 1 2 4 5 8 ) –>  ( 1 2 4 5 8 ) 
Now, the array is already sorted, but our algorithm does not know if it is completed. The
algorithm needs one whole pass without any swap to know it is sorted.
Third Pass: 
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 
( 1 2 4 5 8 ) –> ( 1 2 4 5 8 ) 

Worst and Average Case Time Complexity: O(n*n). Worst case occurs when array is reverse
sorted.
Best Case Time Complexity: O(n). Best case occurs when array is already sorted.
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already
sorted.
Sorting In Place: Yes
Stable: Yes
Due to its simplicity, bubble sort is often used to introduce the concept of a sorting algorithm.  
In computer graphics it is popular for its capability to detect a very small error (like swap of just
two elements) in almost-sorted arrays and fix it with just linear complexity (2n). For example, it
is used in a polygon filling algorithm, where bounding lines are sorted by their x coordinate at a
specific scan line (a line parallel to x axis) and with incrementing y their order changes (two
elements are swapped) only at intersections of two lines

Illustration :

Optimized Implementation: 
The above function always runs O(n^2) time even if the array is sorted. It can be optimized by
stopping the algorithm if inner loop didn’t cause any swap. 

4.3 Insertion Sort

Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in
your hands. The array is virtually split into a sorted and an unsorted part. Values from the
unsorted part are picked and placed at the correct position in the sorted part.
Algorithm 
To sort an array of size n in ascending order: 
1: Iterate from arr[1] to arr[n] over the array. 
2: Compare the current element (key) to its predecessor. 
3: If the key element is smaller than its predecessor, compare it to the elements before. Move the
greater elements one position up to make space for the swapped element.

Example:

Time Complexity: O(n^2) 
Auxiliary Space: O(1)
Boundary Cases: Insertion sort takes maximum time to sort if elements are sorted in reverse
order. And it takes minimum time (Order of n) when elements are already sorted.
Algorithmic Paradigm: Incremental Approach
Sorting In Place: Yes
Stable: Yes
Online: Yes
Uses: Insertion sort is used when number of elements is small. It can also be useful when input
array is almost sorted, only few elements are misplaced in complete big array.
4.4 Merge sort
Like Quicksort, Merge Sort is a Divide and Conquer  algorithm. It divides the input array into two
halves, calls itself for the two halves, and then merges the two sorted halves.  The merge()
function is used for merging two halves. The merge (arr, l, m, r) is a key process that assumes
that arr[l..m] and arr[m+1..r] are sorted and merges the two sorted sub-arrays into one. See the
following C implementation for details.

MergeSort(arr[], l, r)
If r > l
1. Find the middle point to divide the array into two halves:
middle m = l+ (r-l)/2
2. Call merge Sort for first half:
Call mergesort(arr, l, m)
3. Call merge Sort for second half:
Call mergeSort(arr, m+1, r)
4. Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)

The following diagram shows the complete merge sort process for an example array {38, 27, 43,
3, 9, 82, 10}. If we take a closer look at the diagram, we can see that the array is recursively
divided into two halves till the size becomes 1. Once the size becomes 1, the merge processes
come into action and start merging arrays back till the complete array is merged.

4.5 Quick sort


Like Merge Sort, Quicksort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of quicksort
that pick pivot in different ways. 
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.

The key process in quicksort is partition(). Target of partitions is, given an array and an element x
of array as pivot, put x at its correct position in sorted array and put all smaller elements (smaller
than x) before x, and put all greater elements (greater than x) after x. All this should be done in
linear time.

4.6 Heap sort


Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is
similar to selection sort where we first find the minimum element and place the minimum
element at the beginning. We repeat the same process for the remaining elements.

Heap Sort Algorithm for sorting in increasing order: 


1. Build a max heap from the input data. 
2. At this point, the largest item is stored at the root of the heap. Replace it with the last item of
the heap followed by reducing the size of heap by 1. Finally, heapify the root of the tree.  
3. Repeat step 2 while the size of the heap is greater than 1.
How to build the heap? 
Heapify procedure can be applied to a node only if its children nodes are heapified. So the
heapification must be performed in the bottom-up order.
Let’s understand with the help of an example:
Input data: 4, 10, 3, 5, 1
4(0)
/ \
10(1) 3(2)
/ \
5(3) 1(4)

The numbers in bracket represent the indices in the array


representation of data.

Applying heapify procedure to index 1:


4(0)
/ \
10(1) 3(2)
/ \
5(3) 1(4)

Applying heapify procedure to index 0:


10(0)
/ \
5(1) 3(2)
/ \
4(3) 1(4)
The heapify procedure calls itself recursively to build heap
in top down manner.

Time Complexity: Time complexity of heapify is O(Logn). Time complexity of


createAndBuildHeap() is O(n) and the overall time complexity of Heap Sort is O(nLogn).
Advantages of heapsort –

 Efficiency –  The time required to perform Heap sort increases logarithmically while
other algorithms may grow exponentially slower as the number of items to sort
increases. This sorting algorithm is very efficient.
 Memory Usage – Memory usage is minimal because apart from what is necessary to
hold the initial list of items to be sorted, it needs no additional memory space to work
 Simplicity – It is simpler to understand than other equally efficient sorting algorithms
because it does not use advanced computer science concepts such as recursion
Applications of Heapsort 
1. Sort a nearly sorted (or K sorted) array  
2. k largest(or smallest) elements in an array  
Heap sort algorithm has limited uses because Quicksort and Merge sort are better in practice.
Nevertheless, the Heap data structure itself is enormously used.

5. Languages used for building sorting visualizer

5.1. HTML

HTML (Hypertext Markup Language) is the most basic building block of the Web. It defines the
meaning and structure of web content. Other technologies besides HTML are generally used to
describe a web page's appearance/presentation (CSS) or functionality/behaviour (JavaScript).

The first publicly available description of HTML was a document called "HTML Tags", first
mentioned on the Internet by Tim Berners-Lee in late 1991.[6][7] It describes 18 elements comprising
the initial, relatively simple design of HTML. Except for the hyperlink tag, these were strongly
influenced by SGMLguid, an in-house Standard Generalized Markup Language (SGML)-based
documentation format at CERN. Eleven of these elements still exist in HTML 4.[8]

"Hypertext" refers to links that connect web pages to one another, either within a single website or
between websites. Links are a fundamental aspect of the Web. By uploading content to the Internet
and linking it to pages created by other people, you become an active participant in the World Wide
Web.

HTML uses "markup" to annotate text, images, and other content for display in a Web browser.
HTML markup includes special "elements" such
as <head>, <title>, <body>, <header>, <footer>, <article>, <section>, <p>, <div>, <span>, <img>, 
<aside>, <audio>, <canvas>, <datalist>, <details>, <embed>, <nav>, <output>, <progress>, <video
>, <ul>, <ol>, <li> and many others.

An HTML element is set off from other text in a document by "tags", which consist of the element
name surrounded by "<" and ">".  The name of an element inside a tag is case insensitive. That is, it
can be written in uppercase, lowercase, or a mixture. For example, the <title> tag can be written
as <Title>, <TITLE>, or in any other way.

5.2 CSS

CSS (Cascading Style Sheets) is a stylesheet language used to design the webpage to make it
attractive. The reason of using CSS is to simplify the process of making web pages presentable. CSS
allows you to apply styles to web pages. More importantly, CSS enables you to do this independent
of the HTML that makes up each web page.
There are three types of CSS which are given below:
 Inline CSS
 Internal or Embedded CSS
 External CSS

CSS Example

body {
  background-color: lightblue;
}

h1 {
  color: white;
  text-align: center;
}

p {
 font-family: verdana;
  font-size: 20px;
}
5.3 JavaScript

JavaScript is a lightweight, interpreted programming language. It is designed for creating


network-centric applications. It is complimentary to and integrated with Java. JavaScript is very
easy to implement because it is integrated with HTML. It is open and cross-platform.

There are many useful Javascript frameworks and libraries available:

 Angular
 React
 jQuery
 Vue.js
 Ext.js
 Ember.js
 Meteor
 Mithril
 Node.js
 Polymer
 Aurelia
 Backbone.js
It is really impossible to give a complete list of all the available Javascript frameworks and
libraries. The Javascript world is just too large and too much new is happening.

Applications of JavaScript Programming

As mentioned before, JavaScript is one of the most widely used programming


languages (Front-end as well as Back-end). It has its presence in almost every area of software
development. I'm going to list few of them here:

 Client-side validation - This is really important to verify any user input before submitting
it to the server and JavaScript plays an important role in validating those inputs at front-
end itself.
 Manipulating HTML Pages - JavaScript helps in manipulating HTML page on the fly.
This helps in adding and deleting any HTML tag very easily using JavaScript and modify
your HTML to change its look and feel based on different devices and requirements.

 User Notifications - You can use JavaScript to raise dynamic pop-ups on the webpages to
give different types of notifications to your website visitors.

 Back-end Data Loading - JavaScript provides Ajax library which helps in loading back-
end data while you are doing some other processing. This really gives an amazing
experience to your website visitors.

 Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a
web-based slide presentation.

 Server Applications - Node JS is built on Chrome's JavaScript runtime for building fast
and scalable network applications. This is an event-based library which helps in
developing very sophisticated server applications including Web Servers.
Conclusions and Future Work

Through much time and effort, we have successfully created a working web-based
animation tool for visualizing the following sorting algorithms: Selection Sort, Bubble Sort,
Insertion Sort, and Merge/Insertion Sort. Even with its memory overhead, it received
overall positive feedback from the students who explored it. Not surprisingly there was not
a significant difference in learning the material, which reflects what we found in our
previous research. There remains, however, a strong mindset to research and create
animations like these to improve learning in the classroom, which we agree with
completely. Learning how to code a web platform was challenging. we had a previous
internship where we updated the JavaScript on a webpage, but it was much more concise
and did not involve objects and HTML5 for visualizations. The good news is that
JavaScript is still one of the most popular web languages, so we are not too worried about
another big refactor soon for a language update. For my laundry list of future works, the
elephant in the room is to resolve the memory issues. Next would be to modify
Merge/Insertion Sort to reflect a true Merge Sort. After which, we would get Quick Sort up
and running, as the code is already in a state where it would not be too difficult to integrate.
Then, we would add the suggestions listed in the bulleted feedback of Chapter 5 to further
promote usability and understandability. Finally, we would make the web tool public,
realizing my most desired feature of making it public. This would also present some new
challenges. Even though the animation tool works locally, we have unintentionally avoided
the issue of concurrency, where a server can handle multiple requests to the web site by
different users. we will need to give more thought on how to optimize the code so that it
can work with multiple people using it.

You might also like