Sorting Visualizer
Sorting Visualizer
By
Project Guide:
Prof. K. S. Yadav
UNIVERSITY OF MUMBAI
(2024-2025)
CERTIFICATE
Prof. K. S. Yadav
Guide
This project report entitled “SORTING VISUALIZER” by “Anuj Bhaskar Harad (18),
Jay Jitendra Dhamankar (10), Sahil Dhanraj Chandanshive (07), Aditya
Chandrashekhar Mohite (33)” is approved for the T.E. of Computer Engineering.
Examiners
1..........................................
2..........................................
Date.
Place.
DECLARATION
I/We declare that this written submission represents my/our ideas in my/our own
words and where others' ideas or words have been included, I/We have adequately cited and
referenced the original sources. I/We also declare that I/We have adhered to all principles of
academic honesty and integrity and have not misrepresented or fabricated or falsified any
idea/data/fact/source in my/our submission. I/We understand that any violation of the above
will be cause for disciplinary action by the Institute and can also evoke penal action from the
sources which have thus not been properly cited or from whom proper permission has not
been taken when needed.
Date:
ACKNOWLEDGEMENT
I/We are heartily grateful to our project guide Prof. K. S. Yadav, HOD Prof. S. M.
Patil, Principal Dr. V. J. Pillewan (Department of Computer Engineering) for their being
a constant source of encouragement at various stages of the completion of this project.
I/We want to thank our parents and lord, because without their blessing, perhaps we could
do nothing. I/We wish to thank all our friends, colleagues and the campus staff
(Department of Computer Engineering), who have help us with the critical review of this
project including my Friend’s. Their Debugging skills and grateful appreciated. Special
thanks to my Head of the Computer Department Prof. S. M. Patil for his advice and
encouragement. I/We must thankful to the various Authors who have contributed material
for this project.
The Sorting Visualizer is a web-based tool designed to demonstrate the mechanics of various
sorting algorithms through real-time visualizations. This project aims to enhance the
understanding of algorithmic processes by providing an intuitive and engaging platform for
users to observe how different sorting techniques like Bubble Sort, Merge Sort, Quick Sort,
and Heap Sort operate on unsorted data sets.
The implementation of these algorithms draws heavily from the foundational work in
Introduction to Algorithms by Cormen et al. (2009), which provides in-depth explanations of
the algorithms' complexities and operations. The project also uses JavaScript extensively for
creating dynamic and interactive animations, following best practices outlined in Flanagan’s
JavaScript: The Definitive Guide (2006). The backend logic for handling algorithm execution
is built using Python and Flask, as described in Flask Web Development by Grinberg (2018).
Recent research, such as the hybrid sorting technique proposed by Gupta and Bhatia (2017),
further informs this project by highlighting optimized approaches to traditional sorting
algorithms. The visualizer allows users to interactively explore how different algorithms
perform under various conditions, making the learning process both efficient and insightful.
This project effectively combines modern web development techniques with classic
algorithm theory to deliver an educational platform that brings sorting algorithms to life.
i
LIST OF FIGURES
ii
INTRODUCTION
1.1 Introduction :-
The application is built using HTML, CSS, JavaScript, and Python Flask. The frontend
handles the user interface and visualization, while the backend provides the necessary data
and logic for the sorting algorithms. The Sorting Visualizer aims to be a valuable educational
tool for students, developers, and anyone interested in learning about sorting algorithms.
1.1 Motivation :-
The primary motivation behind creating the Sorting Visualizer web application is to
provide a more engaging and effective way to learn about sorting algorithms. Traditional
methods of learning about sorting algorithms often involve reading textbooks or attending
lectures, which can be abstract and difficult to understand. By visualizing the sorting process,
1
the Sorting Visualizer aims to make these concepts more concrete and easier to grasp.
Additionally, the application can be used to compare the performance of different sorting
algorithms. This can help users understand the strengths and weaknesses of each algorithm
and choose the most appropriate one for a given task.
Sorting algorithms play a fundamental role in computer science, as they are essential for
organizing and processing data efficiently. They are used in a wide range of applications,
including database systems, search engines, and data analysis tools. By arranging data in
a specific order, sorting algorithms enable faster searching, retrieval, and manipulation of
information. Additionally, they are often used as building blocks for other algorithms
and data structures, making them a crucial component of many computer science
problems.
Sorting algorithms are fundamental to computer science and data structures, forming
the basis of various computational tasks. However, understanding how these algorithms work
can be challenging, especially for beginners, as the logic is abstract and happens behind the
scenes. There is a need for a visual and interactive tool that can help students, developers, and
enthusiasts better comprehend the process and performance of various sorting algorithms by
showing how elements are compared, moved, and sorted step-by-step.
1.4 Objectives :-
The goal of this project is to develop a Sorting Visualizer Web Application that
allows users to select different sorting algorithms and visualize the sorting process in real-
time. This tool will provide an educational and interactive platform for understanding the
behavior and efficiency of sorting algorithms, such as Bubble Sort, Merge Sort, Quick Sort,
and Insertion Sort.
2
1.5 Technology Used :-
1. Flask: Lightweight web framework in Python for handling backend logic and serving
sorting algorithms.
2. Python: Primary programming language for implementing sorting algorithms
(Bubble Sort, Merge Sort, Quick Sort, Insertion Sort).
3. HTML/CSS: Used for structuring and styling the frontend interface, ensuring a
responsive and modern design.
4. JavaScript: Responsible for frontend interactivity, sorting animations, and managing
user inputs.
5. AJAX/Fetch API: Enables asynchronous communication between the frontend and
backend, allowing real-time updates without page reloads.
3
1.6 Scope :-
Algorithm Visualization:Users can select from multiple sorting algorithms such as Bubble Sort,
Merge Sort, Quick Sort, and Insertion Sort to visualize the sorting process step-by-step.
Customizable Array Sizes: Users can dynamically generate arrays of varying sizes,
allowing them to observe the sorting performance and behavior for different data sets (small
to large).
Sorting Speed Control: Users can adjust the speed of the sorting visualization (slow,
medium, fast), allowing them to slow down or speed up the process for better understanding.
Backend Sorting Logic: The backend processes sorting algorithms in Python and serves
the sorted arrays to the frontend via Flask.
Educational Tool: Serves as an interactive educational tool for students, developers, and
learners to understand how sorting algorithms work.
Scalability: The project can be expanded to include more sorting algorithms or other data
structure visualizations.
4
1.7 Proposed System :-
5
REVIEW OF LITERATURE
The development of sorting algorithms has been a fundamental aspect of computer science,
providing the groundwork for efficient data organization and retrieval. Various studies and
research papers have explored sorting algorithms, their complexities, and their practical
applications in different fields.
Educational Tools: The use of interactive applications for teaching algorithms has gained
traction, with various projects demonstrating how visualization can aid learning. For instance,
6
programs like VisuAlgo and SortingVisualizer have shown that incorporating visual elements
significantly increases student engagement and retention of information about sorting
techniques.
7
REQUIREMENT ANALYSIS
Software Requirements deal with defining software resources requirements and pre-requisites
that needed to be install on a computer to provide optional functioning of an application.
Language Python
Integrated Development Environment (IDE) or text editor for code development (e.g.,
VSCode, PyCharm, Sublime Text)
Operating system compatible with Python and required libraries (e.g., Windows)
3.2 Hardware Requirements
8
The most set of requirements defined by any operating system or software application is the
physical computer resources, also known as hardware.
RAM 4/8GB
9
3.3 Functional & Non-Functional Requirements
The application shall provide a clean and intuitive user interface that is easy to
navigate.
The main dashboard shall display options for selecting sorting algorithms, array size,
and sorting speed.
The application shall allow users to choose from multiple sorting algorithms (e.g.,
Bubble Sort, Merge Sort, Quick Sort, Insertion Sort).
Array Generation
Sorting Visualization
The application shall animate the sorting process in real-time, showing step-by-step
movements of array elements as they are compared and swapped.
Speed Control
The application shall allow users to select the speed of the sorting animation through a
dropdown menu.
The sorting visualization speed shall adjust according to the user’s selection.
10
3.3.2 Non-Functional Requirements:
Performance
The application shall handle user requests with minimal latency, ensuring a
responsive experience during array generation and sorting visualizations.
Sorting visualizations should be rendered smoothly without significant delays,
maintaining an acceptable frame rate for animations.
Scalability
Reliability
The application shall be reliable, ensuring that sorting algorithms execute correctly
and consistently without errors.
It shall maintain data integrity, accurately displaying both the unsorted and sorted
arrays.
Usability
The user interface shall be intuitive and easy to navigate, enabling users to interact
with the application without requiring extensive instructions.
Help documentation or tooltips shall be provided to assist users in understanding how
to use the features effectively.
Maintainability
The application code shall be well-structured and documented, allowing for easy
updates, bug fixes, and feature enhancements in the future.
The separation of concerns shall be implemented, keeping frontend and backend code
modular for easier maintenance.
11
Security
Compatibility
The application shall be compatible with major web browsers (e.g., Chrome, Firefox,
Safari) and function consistently across them.
It shall also be designed to work on various operating systems (e.g., Windows,
macOS, Linux).
Accessibility
The application shall comply with web accessibility standards (e.g., WCAG) to ensure
that users with disabilities can use it effectively.
All interactive elements shall be keyboard navigable, and screen readers shall provide
meaningful descriptions.
12
DESIGN & PLANNING
4.1 Algorithm
1. Start the Application: Open the web application in a browser. The main dashboard
will display options for array size, sorting speed, and sorting algorithms.
The selected speed determines the pace at which sorting steps are animated.
Step 5: The sorting algorithm will be executed on the array, and each step of the
algorithm will be visually animated. Bars representing the elements will move and
swap positions based on the selected sorting algorithm.
Step 6: During the sorting process, the visualization updates continuously until the
array is fully sorted. The speed of the sorting process is adjusted according to the
user-selected speed.
7. Completion of Sorting
Step 7: Once the sorting is complete, the fully sorted array is displayed on the screen.
The user can see the visual transformation of the array from an unsorted state to a
sorted state.
Step 8: The user can regenerate a new array by clicking the “Generate new Array”
button. The user may then select a different sorting algorithm to compare its
performance and visualization with previous ones.
14
4.2 Flowchart
15
4.3 UML Diagram
16
4.3.2 UML Use case Diagram
17
4.4 Data Flow Diagram
18
4.5 UI Design
19
Fig. 4.5.3 Before Sorting
20
4.6 Gantt Chart
21
IMPLEMENTATION
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sorting Visualizer</title>
<link href = '/static/style.css' rel = 'stylesheet'>
<script src = "{{ url_for('static', filename='script.js') }}"></script>
</head>
<body>
<header>
<div id = 'sort_dashboard'>
<h1 id = 'logo'>Sorting Visualizer</h1>
<div class = 'input'>
<label for="size" >Size :</label>
<select name="size" id = "size">
<option value="5">5</option>
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>
<div class = "input">
<label for = "algo">Algorithm :</label>
<option value = "bubble">Bubble Sort</option>
22
<option value = "selection">Selection Sort</option>
<option value = "insertion">Insertion Sort</option>
<option value = "merge">Merge Sort</option>
</select>
</div>
<button id = 'generate_btn' class = 'input'
onclick="sendData()">Generate</button>
<button id = 'sort_btn' class = 'input' onclick =
"startAnimation()">Sort</button>
</div>
</header>
<content>
<div id='sort_scr' class='screen'></div>
</content>
<footer>
</footer>
</body>
</html>
static/style.css
* {
color : #0f454b;
padding : 0px;
margin : 0px;
border : 0px;
font-weight: bolder;
}
body {
background-color: #edf6f9;
position: relative;
min-height: 50vh;
text-align: center;
}
header,#sort_menu{
background-color: #83c5be;
}
h1{
text-align : center;
margin-top: 20px;
margin-bottom: 10px;
}
23
.input{
display : inline-block;
margin-top : 20px;
margin-bottom : 20px;
margin-left : 6%;
margin-right:6%;
}
#generate_btn,#sort_btn{
padding: 10px 20px
}
#sort_scr{
display: flex;
justify-content: space-around;
align-items: flex-end;
height: 200px;
width: 100%;
border: 1px solid #ddd;
}
button{
border : solid 2px black;
border-radius: 15px;
}
button:active{
color : white;
background-color: #0f454b;
}
static/script.js
function sendData() {
const size = document.getElementById("size").value;
const algo = document.getElementById("algo").value;
const data = {
'size': size,
'algo': algo
};
24
fetch('/getdt', {
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
body: JSON.stringify(data)
})
.then(function (response) {
if (response.ok) {
return response.json();
} else {
throw new Error('Failed to fetch sorting data from server');
}
})
.then(function (responseData) {
console.log("Response received:", responseData);
steps = responseData.sort_steps;
const barHeight = responseData.array;
barContainer = document.getElementById('sort_scr');
barContainer.innerHTML = '';
barHeight.forEach(height => {
const bar = document.createElement("div");
bar.classList.add("bar");
bar.style.height = `${height}px`;
bar.style.width = `${(100 / barHeight.length) - 1}%`;
bar.style.display = 'inline-block';
bar.style.background = '#168aad';
barContainer.appendChild(bar);
});
})
.catch(function (error) {
console.error("Error during fetch:", error);
});
}
function startAnimation() {
if (steps.length === 0) {
console.error("No sorting steps available. Please generate bars
first.");
return;
}
animateSorting(steps, barContainer);
}
bars.forEach((bar,i) => {
setTimeout(() => {
bars[i].style.background = '#7ae582'
} , delay*i)
});
}
sorting.py
class SortingModule():
def __init__(self):
self.steps = []
def bubble_sort(self,arr):
for i in range(0,len(arr)-1):
for j in range(0,len(arr)-i-1):
if arr[j] > arr[j+1]:
temp = arr[j]
arr[j] = arr[j+1]
arr[j+1] = temp
self.steps.append(arr.copy())
def selection_sort(self,arr):
for i in range(len(arr)-1):
min_element = arr[i]
for j in range(i+1,len(arr)):
if arr[j] < min_element:
min_element = arr[j]
min_index = j
if min_element != arr[i]:
temp = arr[i]
arr[i] = min_element
arr[min_index] = temp
self.steps.append(arr.copy())
26
def insertion_sort(self,arr):
for i in range(0,len(arr)):
j = i
while j>0 and arr[j-1] > arr[j]:
temp = arr[j]
arr[j] = arr[j-1]
arr[j-1] = temp
j-=1
self.steps.append(arr.copy())
def merge(self,arr,low,mid,high):
temp = []
left = low
right = mid+1
while left<=mid:
temp.append(arr[left])
left+=1
while right<=high:
temp.append(arr[right])
right+=1
for i in range(low,high+1):
arr[i] = temp[i-low]
self.steps.append(arr.copy())
def merge_sort(self,arr,low,high):
if low >= high :
return
mid = (low+high)//2
self.merge_sort(arr, low, mid)
self.merge_sort(arr, mid+1, high)
self.merge(arr, low, mid, high)
27
app.py
from flask import Flask,request,url_for,render_template,jsonify
from sorting import SortingModule
from random import randint
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
sort = SortingModule()
array = None
@app.route('/')
def start():
return render_template('index.html')
def select_algo(algo):
if algo == 'bubble':
bubble_algo()
elif algo == 'selection':
selection_algo()
elif algo == 'insertion':
insertion_algo()
elif algo == 'merge':
merge_algo()
elif algo == 'quick':
quick_algo()
def bubble_algo():
sort.steps.clear()
sort.bubble_sort(array)
def selection_algo():
sort.steps.clear()
sort.selection_sort(array)
def insertion_algo():
sort.steps.clear()
sort.insertion_sort(array)
def merge_algo():
sort.steps.clear()
sort.merge_sort(array,0,len(array)-1)
def quick_algo():
pass
@app.route('/getdt', methods=['POST'])
28
def process():
try:
data = request.json
print("Received data:", data)
if not data:
return jsonify({'error': 'No data received'}), 400
size = int(data.get('size'))
algo = data.get('algo')
global array
array = [randint(10, 100) for _ in range(size)]
unsorted_array = array.copy()
select_algo(algo)
return jsonify({
'message': 'Data received successfully',
'array' : unsorted_array,
'sort_steps' : sort.steps
}), 200
except Exception as e:
print(f"Error occurred: {e}")
return jsonify({'error': 'Internal Server Error', 'details': str(e)}),
500
if __name__ == "__main__":
app.run()
29
FUTURE ENHANCEMENT
The Sorting Visualizer Web Application has significant potential for future improvements
and feature expansions. Below are some proposed future enhancements:
Addition of More Sorting Algorithms: Introduce advanced sorting algorithms such as Heap
Sort, Radix Sort, and Counting Sort to broaden the range of algorithms that can be visualized.
Algorithm Performance Metrics: Show performance metrics, such as the time complexity
(number of comparisons or swaps) and space complexity, in real-time during the sorting
process.
Custom Array Input: Allow users to input their own custom arrays or lists of numbers to
visualize how different algorithms sort user-defined data.
31
CONCLUSION
The Sorting Visualizer Web Application successfully bridges the gap between theoretical
understanding and practical application of sorting algorithms. By providing an interactive and visually
engaging platform, it helps users visualize and comprehend the step-by-step processes behind various
sorting techniques, making abstract concepts more tangible. The application not only demonstrates the
fundamental workings of algorithms like Bubble Sort, Merge Sort, and Quick Sort but also allows
users to explore their efficiency through real-time animations.
The use of Python in the backend to execute sorting algorithms and JavaScript to manage
frontend interactivity ensures a smooth, responsive experience. This project demonstrates
how a combination of backend logic and frontend visualization can create a powerful
educational tool. With its intuitive interface, the application makes learning sorting
algorithms more accessible for students, educators, and programming enthusiasts alike.
Looking forward, the potential for future enhancements such as additional algorithms,
interactive learning features, and algorithm performance comparisons promises to expand the
scope and utility of the application. Overall, this project provides a strong foundation for
understanding sorting algorithms, while offering numerous opportunities for future
development and innovation.
32
Drawing from the foundational work of Cormen et al. (2009) on algorithms, Flanagan's
(2006) insights on JavaScript, and Grinberg's (2018) practical guide to Flask, the project
offers a seamless blend of academic knowledge and real-world application. Additionally, the
recent hybrid sorting techniques by Gupta and Bhatia (2017) emphasize the importance of
continuous innovation in sorting algorithms, which the visualizer integrates by demonstrating
their practical utility.
Overall, the Sorting Visualizer not only aids in the educational process but also serves as a
powerful tool for understanding complex algorithmic structures, highlighting the importance
of interactive learning in computer science. Through this project, users can develop a deeper
appreciation for algorithms and their impact on computational efficiency.
33
REFERENCE
1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., and Stein, C., 2009, Introduction to
Algorithms, 3rd ed., MIT Press, Cambridge, MA.
2. Flanagan, D., 2006, JavaScript: The Definitive Guide, 6th ed., O'Reilly Media, Sebastopol,
CA.
3. Grinberg, M., 2018, Flask Web Development: Developing Web Applications with Python, 2nd
ed., O'Reilly Media, Sebastopol, CA.
4. Mozilla Developer Network (MDN Web Docs), n.d., "JavaScript Event Listeners and Fetch
API," https://developer.mozilla.org/ (Accessed October 23, 2024).
7. Gupta, S., and Bhatia, P., 2017, “Optimized Sorting Algorithm Based on Hybrid
Approach,” 2017 International Conference on Computing, Communication, and
Automation (ICCCA), IEEE, pp. 1-5, https://ieeexplore.ieee.org/document/8075355
34