0% found this document useful (0 votes)
91 views

Sorting Visualizer

A web application
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Sorting Visualizer

A web application
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

SORTING VISUALIZER

MINI PROJECT REPORT

submitted in partial fulfillment of the requirements

of the Third Year of Bachelor of Computer Engineering

By

Sahil Dhanraj Chandanshive


Roll No:-07
Jay Jitendra Dhamankar
Roll No:-10

Anuj Bhaskar Harad


Roll No:-18

Aditya Chandrashekhar Mohite


Roll No:-33

Project Guide:
Prof. K. S. Yadav

DEPARTMENT OF COMPUTER ENGINEERING

KONKAN GYANPEETH COLLEGE OF ENGINEERING

UNIVERSITY OF MUMBAI
(2024-2025)
CERTIFICATE

This is to certify the project entitled “SORTING VISUALIZER” is a bonafide work of


“Anuj Bhaskar Harad (18),Jay Jitendra Dhamankar(10), Sahil Dhanraj Chandanshive
(07), Aditya Chandrashekhar Mohite (33)” submitted to be University of Mumbai in
partial fulfillment of the requirement for the award of the “T.E.” in “Computer
Engineering”.

Prof. K. S. Yadav
Guide

Prof. S. M. Patil Dr. V. J. Pillewan


Head of Department Principal
KONKAN GYANPEETH COLLEGE OF ENGINEERING, KARJAT.
(Affiliated to University of Mumbai, Approved by A.I.C.T.E., New Delhi.
Konkan Gyanpeeth Shaikshanik Sankul, Vengaon Road, Dahivali, Karjat, Dist.-Raigad.410201. (M.S.)

Department Of Computer Engineering

Project Report Approval

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.

Sahil Dhanraj Chandanshive (07) ----------------------------------------


Jay Jitendra Dhamankar (10) ----------------------------------------
Anuj Bhaskar Harad (18) -----------------------------------------
Aditya Chandrashekhar Mohite (33) -----------------------------------------
(Signature/s)

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.

Sahil Dhanraj Chandanshive (07)


Jay Jitendra Dhamankar (10)
Anuj Bhaskar Harad (18)
Aditya Chandrashekhar Mohite (33)
INDEX

CONTENTS Page No.


Abstract………………………………………………………………………………i
List of Figures……………………………………………………………………….ii
1. INTRODUCTION…………………………………………………..…………1-5
1.1. Introduction & Motivation…………………………………...……….....1
1.2. Existing System……………………………………………...………….2
1.3. Problem Statement…………………………………………………...….2
1.4 Objectives……………………………………………………………......2
1.5 Technology Used…………………………………………………….......3
1.6 Scope………………………………………………………………….….4
1.7 Proposed System………………………………………………………....5
2. REVIEW OF LITERATURE…………………………………………………6-7
3. REQUIREMENT ANALYSIS……………………………………………….8-12
3.1.Software Requirements………………………………………...…….......8
3.2.Hardware Requirements……………………………………………….…9
3.3.Functional & Non-Functional Requirements………………………..10-11
4. DESIGN & PLANNING………………………………………………….....13-21
4.1 Algorithm…………………………………………………………….13-14
4.2 Flowchart………………………………………………………………...15
4.3 UML Diagram…………………………………………………………...16
4.4 Dataflow Diagram…………………………………………………….…18
4.5 UI Design…………………………………………………………….….19
4.6 Gantt Chart……………………………………………………………....21
5. IMPLEMENTATION ………………….……………………………….….22-29
6. FUTURE ENHANCEMENTS……………………………………………...30-31
7. CONCLUSION & REFERENCES……………………………...................32-34
ABSTRACT

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

Figures Page No.


Fig 4.2.1 Flowchart of Sorting Visualizer 15
Fig 4.3.1 UML Class Diagram 16
Fig. 4.3.2 UML Usecase Diagram 17
Fig. 4.4.1 Sorting Module 18
Fig. 4.5.1 Size Dropdown 19
Fig. 4.5.2 Algorithm Dropdown 19
Fig. 4.5.3 Before Sorting 20
Fig. 4.5.4 After Sorting 20
Fig. 4.6.1 Gantt Chart 21

ii
INTRODUCTION

1.1 Introduction :-

Sorting Visualizer is an interactive web application designed to provide a clear and


intuitive understanding of various sorting algorithms. It offers a visual representation of the
sorting process, allowing users to observe the step-by-step execution of different algorithms.
By visualizing the sorting algorithms, users can gain insights into their principles, compare
their performance, and learn about the concepts of computer science.

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.

1.2 Existing System :-

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.

1.3 Problem Statement:-

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 :-

The project utilizes several technologies to develop a comprehensive Sorting


Visualizer Web Application. The backend logic is handled using Flask, a lightweight web
framework in Python, which efficiently processes sorting algorithms and serves the data to
the frontend. Python serves as the primary programming language for implementing the
sorting algorithms such as Bubble Sort, Merge Sort, Quick Sort, and Insertion Sort. The
frontend of the application is built using HTML, CSS, and JavaScript, creating an interactive
and visually appealing user interface. JavaScript is responsible for managing user interactions
and dynamically animating the sorting process on the screen. AJAX or Fetch API is used to
establish asynchronous communication between the frontend and backend, allowing the
frontend to request sorted arrays from the server in real-time without refreshing the page.
This combination of technologies ensures smooth interactivity, real-time visualization, and
seamless user experience.

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).

 Real-Time Sorting Animations: Visual representations of the sorting process are


displayed on the screen through animated bars, showing the step-by-step comparison and
swapping of elements.

 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.

 User Interaction: A user-friendly interface that includes buttons to trigger different


algorithms and dropdowns to select array sizes and sorting speeds.

 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.

 Cross-Browser Compatibility: The application is designed to work across different


browsers and devices, ensuring accessibility for a wide range of users.
.

4
1.7 Proposed System :-

The proposed Sorting Visualizer Web Application is designed to offer users an


interactive platform for visualizing various sorting algorithms in real-time. It allows
users to choose from algorithms like Bubble Sort, Merge Sort, Quick Sort, and
Insertion Sort, while dynamically generating arrays of different sizes for sorting. The
system will visually animate the sorting process using JavaScript, providing step-by-
step feedback of how elements are compared and swapped during sorting. Users can
also control the speed of the visualization, adjusting the pace to better understand each
algorithm’s behavior. The backend of the system, developed in Flask using Python,
will handle the logic for sorting and return sorted arrays to the frontend upon request.
With a user-friendly interface, the web application will serve as an educational tool to
help users grasp the workings of sorting algorithms while being responsive and
accessible across multiple devices.

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.

Sorting Algorithms Overview: Numerous publications, such as "Introduction to


Algorithms" by Cormen et al., provide comprehensive insights into various sorting
algorithms, including their time and space complexities. This foundational knowledge is
crucial for understanding the strengths and weaknesses of each algorithm in real-world
scenarios.

Visualization of Algorithms: Research by Tufte (2001) emphasizes the importance of data


visualization in understanding complex information. Visualizing sorting algorithms enhances
learners' comprehension by presenting abstract concepts in a tangible format. Studies indicate
that students benefit from interactive visual tools that illustrate algorithmic processes, leading
to improved learning outcomes.

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.

Impact of User Interaction: Research conducted by Kelleher and Pausch (2005) on


programming education highlights the effectiveness of hands-on learning experiences.
Applications that allow users to interact with algorithms—such as adjusting input sizes and
speeds—foster a deeper understanding of algorithm performance and behavior.

Technological Advancements:Utilizing frameworks like Flask for backend processing and


JavaScript for frontend interactivity has become increasingly popular in developing
educational software. This approach enhances accessibility, enabling users to engage with
sorting algorithms from any device with internet access.

7
REQUIREMENT ANALYSIS

3.1 Software Requirements

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.

Operating System Windows 7/10 or macOS or Linux

Language Python

PIP modules flask ,flask_cors, random

 Python programming language (version 3.x)

 pip for installing paclages and libraries

 Flask Framework for server side Logic

 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.

Processor Intel i3 or equivalent AMD processor

RAM 4/8GB

 Minimum dual-core processor (e.g., Intel Core i3 or equivalent AMD processor)


 At least 4GB of RAM for smooth application performance
 Adequate storage space for project files and databases (minimum requirements)
 Display screen with a resolution of 1280x800 pixels or higher for optimal GUI
viewing

9
3.3 Functional & Non-Functional Requirements

3.3.1 Functional Requirements:

User Interface (UI)

 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.

Sorting Algorithm Selection

 The application shall allow users to choose from multiple sorting algorithms (e.g.,
Bubble Sort, Merge Sort, Quick Sort, Insertion Sort).

Array Generation

 The application shall provide a functionality to generate a random array based on


user-selected size.
 The array shall be visually represented as vertical bars or lines on the screen.

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

 The application shall be able to accommodate an increasing number of users without


degrading performance, allowing for future growth in user base and features.

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

 The application shall implement measures to prevent common security vulnerabilities


(e.g., Cross-Site Scripting (XSS), Cross-Site Request Forgery (CSRF)).
 User data shall be handled securely, ensuring no sensitive information is stored or
transmitted without proper encryption.

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.

2. User Interaction with the Interface:


Step 1: Select the size of the array from the dropdown menu (e.g., 10, 25, 50, etc.).
The selected size determines the number of bars or lines that represent the array
elements.
Step 2: Click the “Generate new Array” button. This dynamically generates an array
with random values and displays it as vertical bars on the screen.

3. Choose Sorting Speed


Step 3: Select the speed of sorting from the dropdown menu (e.g., 0.5x, 1x, 2x).

The selected speed determines the pace at which sorting steps are animated.

4. Select a Sorting Algorithm


Step 4: Click on the button corresponding to the desired sorting algorithm (e.g.,
Bubble Sort, Merge Sort, Quick Sort, etc.). The button click triggers the selected
sorting algorithm.
13
5. Sorting Visualization

 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.

6. Real-time Sorting and Animation

 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.

8. Repeat or Try Other Algorithms

 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

Fig. 4.2.1 Flowchart of Sorting Visualizer

15
4.3 UML Diagram

Fig, 4.3.1 UML Class Diagram

16
4.3.2 UML Use case Diagram

17
4.4 Data Flow Diagram

4.4.1 Sorting Module

18
4.5 UI Design

Fig. 4.5.1 Size Dropdown

Fig. 4.5.2 Algorithm Dropdown

19
Fig. 4.5.3 Before Sorting

Fig. 4.5.4 After Sorting

20
4.6 Gantt Chart

Fig. 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

let steps = [];


let barContainer = null;

function sendData() {
const size = document.getElementById("size").value;
const algo = document.getElementById("algo").value;
const data = {
'size': size,
'algo': algo
};

console.log("Sending data:", data);

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);
}

function animateSorting(steps, barContainer) {


25
const bars = Array.from(barContainer.children);
const delay = 200;

steps.forEach((step, index) => {


setTimeout(() => {
step.forEach((height, i) => {
bars[i].style.height = `${height}px`;
});
}, delay * index);
});

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 and right<=high:

if arr[left] <= arr[right]:


temp.append(arr[left])
left+=1
else:
temp.append(arr[right])
right+=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.

Detailed Algorithm Explanations: Add a feature that displays step-by-step textual


explanations of each sorting algorithm as the visualization progresses, helping users
understand the algorithm’s logic more effectively.

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.

Sorting Algorithm Comparisons: Implement a side-by-side comparison feature, where


multiple sorting algorithms are visualized concurrently, helping users compare their
efficiency and behavior with the same data set.
30
Data Export Functionality: Provide an option to export the sorting process and results, such
as generating a report or downloading a visual representation (image or video) of the sorting
animation.

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).

5. Knutson, D., 2019, "Building a Sorting Visualizer with JavaScript," Medium,


https://medium.com/ (Accessed October 23, 2024).

6. Stack Overflow, n.d., "Various Topics on Flask, JavaScript, and Python,"


https://stackoverflow.com/ (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

You might also like