
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting arrays using bubble sort in JavaScript
We are required to write a JavaScript function that takes in an array of literals and sorts it using bubble sort.
Example
The code for this will be −
const arr = [4, 56, 4, 23, 8, 4, 23, 2, 7, 8, 8, 45]; const swap = (items, firstIndex, secondIndex) => { var temp = items[firstIndex]; items[firstIndex] = items[secondIndex]; items[secondIndex] = temp; }; const bubbleSort = items => { var len = items.length, i, j; for (i=len-1; i >= 0; i--){ for (j=len-i; j >= 0; j--){ if (items[j] < items[j-1]){ swap(items, j, j-1); } } } return items; }; console.log(bubbleSort(arr));
Output
The output in the console −
[ 2, 4, 4, 4, 7, 8, 8, 8, 23, 23, 45, 56 ]
- Related Questions & Answers
- 8085 Program to perform sorting using bubble sort
- Sorting Array without using sort() in JavaScript
- Bubble Sort
- Code to implement bubble sort - JavaScript
- Bubble sort in Java.
- JavaScript Bubble sort for objects in an array
- Sorting an array of literals using quick sort in JavaScript
- Bubble Sort program in C#
- Bubble Sort in Go Lang
- Sorting arrays by two criteria in JavaScript
- Write a Golang program to sort an array using Bubble Sort
- Difference Between Bubble Sort and Selection Sort
- 8085 program for bubble sort
- Python Program for Bubble Sort
- Sorting Arrays in Perl
Advertisements