
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Code to implement bubble sort - JavaScript
We are required to write a JavaScript function that takes in an array of literals and sorts it using bubble sort. In Bubble Sort, each pair of adjacent elements is compared and the elements are swapped if they are not in order.
Example
Let’s write the code for this function −
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 Articles
- Java program to implement bubble sort
- C++ Program to Implement Bubble Sort
- Implement Bubble sort with negative and positive numbers – JavaScript?
- Bubble Sort
- Sorting arrays using bubble sort in JavaScript
- JavaScript Bubble sort for objects in an array
- Bubble sort in Java.
- Program to implement Bucket Sort in JavaScript
- How to implement quick sort in JavaScript?
- How to implement insertion sort in JavaScript?
- How to implement merge sort in JavaScript?
- Difference Between Bubble Sort and Selection Sort
- Python Program for Bubble Sort
- Bubble Sort program in C#
- 8085 program for bubble sort

Advertisements