The following example code demonstrates How to Sort an Array of Elements Using JavaScript.
Basically, in this example, we use Bubble Sort to sort an array of elements. To begin with, first we create an array of ten elements. Also, note that, we have three buttons on the page. When user clicks on the first button, its event handler is called. In order to input elements, it executes a for loop that iterates 10 times to accept 10 numbers from the user. The values entered by the user are converted to numeric values using the Number() function.
Similarly, the second button calls a function that displays these values. While, the third button calls a function named sortElements() that perform bubble sort and displays the sorted array in another paragraph.
<html>
<head>
<title>Sorting in JavaScript</title>
<script>
arr=Array(10);
function sortElements(x)
{
str="Sorted Elements: ";
var n=10;
for(i=0;i<n-1;i++)
{
for(j=0;j<n-i-1;j++)
{
if(arr[j]>arr[j+1])
{
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
}
for(i=0;i<10;i++)
{
str+=arr[i]+" ";
}
var x=document.getElementById('d2');
x.innerHTML+=str;
}
function inputElements()
{
for(i=0;i<10;i++)
{
arr[i]=Number(prompt('Enter Element '+(i+1)));
}
}
function displayElements()
{
var str="";
for(i=0;i<10;i++)
{
str+=arr[i]+" ";
}
var x=document.getElementById('d1');
x.innerHTML+=str;
}
</script>
<style>
div{
margin: 100px;
padding: 50px;
border: 2px black solid;
text-align: center;
}
</style>
</head>
<body>
<div>
<button onclick="inputElements()">Input Elements</button>
<button onclick="displayElements()">Display Elements</button>
<button onclick="sortElements()">Sort Elements</button>
<p id="d1">Original Array: </p>
<p id="d2"></p>
</div>
</body>
</html>
Output
Further Reading
Evolution of JavaScript from ES1 to ES2020
Introduction to HTML DOM Methods in JavaScript
Understanding Document Object Model (DOM) in JavaScript
What is Asynchronous JavaScript?
Understanding HTTP Requests and Responses
- AI
- Android
- Angular
- ASP.NET
- Augmented Reality
- AWS
- Bioinformatics
- Biometrics
- Blockchain
- Bootstrap
- C
- C#
- C++
- Cloud Computing
- Competitions
- Courses
- CSS
- Cyber Security
- Data Science
- Data Structures and Algorithms
- Data Visualization
- Datafication
- Deep Learning
- DevOps
- Digital Forensic
- Digital Trust
- Digital Twins
- Django
- Docker
- Dot Net Framework
- Drones
- Elasticsearch
- ES6
- Extended Reality
- Flutter and Dart
- Full Stack Development
- Git
- Go
- HTML
- Image Processing
- IoT
- IT
- Java
- JavaScript
- Kotlin
- Latex
- Machine Learning
- MEAN Stack
- MERN Stack
- Microservices
- MongoDB
- NodeJS
- PHP
- Power Bi
- Projects
- Python
- Quantum Computing
- React
- Robotics
- Rust
- Scratch 3.0
- Shell Script
- Smart City
- Software
- Solidity
- SQL
- SQLite
- Tecgnology
- Tkinter
- TypeScript
- VB.NET
- Virtual Reality
- Web Designing
- WebAssembly
- XML