Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until no swaps are needed, which indicates that the list is sorted. In this article, we’ll explore a basic version of the bubble sort algorithm in JavaScript to sort a list of numbers in ascending order. We’ll then explore several variations, including sorting in descending order, optimizing the algorithm for better performance, and using it with different data types.
Prerequisites:
- Introduction to Bubble Sort Algorithm
- How Bubble Sort Works: Step-by-Step Explanation
- Bubble Sort Algorithm: Pseudocode and Explanation
Basic Bubble Sort Implementation
Let’s start with the most straightforward implementation of bubble sort. This version sorts an array in ascending order by comparing adjacent elements and swapping them if they are out of order.
function bubbleSort(arr) {
// `arr` is the array that we want to sort
let n = arr.length; // Get the length of the array
// The outer loop goes through each element in the array
// After each pass, the largest unsorted element is placed at the end
for (let i = 0; i < n - 1; i++) {
// The inner loop compares each adjacent element and swaps them if needed
// As the largest element is bubbled to end with each outer loop, we exclude the sorted elements from comparison using `n-i-1`
for (let j = 0; j < n - i - 1; j++) {
// Compare the adjacent elements
// If the first element is larger than the second element then swap
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1] using a temporary variable
let temp = arr[j]; // Store the value of arr[j] in temp
arr[j] = arr[j + 1]; // Assign the value of arr[j+1] to arr[j]
arr[j + 1] = temp; // Assign the value of temp (originally arr[j]) to arr[j+1]
}
}
}
return arr; // return the sorted array
}
// Example of using bubble sort on an array of numbers
let arr = [64, 34, 25, 12, 22, 11, 90];
let sortedArr = bubbleSort(arr); // calling the bubbleSort method on the array of numbers
console.log("Sorted array is:", sortedArr);
// Output: Sorted array is: [11, 12, 22, 25, 34, 64, 90]
In this basic implementation:
- We define a function
bubbleSort(arr)
that takes an arrayarr
as input. - We get the length of the array using
arr.length
and store it in the variablen
. - The outer loop
for (let i = 0; i < n - 1; i++)
iterates through each element of the array. - The inner loop
for (let j = 0; j < n - i - 1; j++)
compares each adjacent element and swaps them if needed. - If the element at index
j
is greater than the element at indexj+1
, then we swap them using a temporary variabletemp
.
Sorting in Descending Order
To sort elements from largest to smallest, we modify the comparison operator from >
to <
. This adjusted version can be useful for ranking systems or displaying data from highest to lowest values.
function bubbleSortDescending(arr) {
// `arr` is the array that we want to sort
let n = arr.length; // Get the length of the array
// The outer loop goes through each element in the array
// After each pass, the smallest unsorted element is placed at the end
for (let i = 0; i < n - 1; i++) {
// The inner loop compares each adjacent element and swaps them if needed
// As the smallest element is bubbled to end with each outer loop, we exclude the sorted elements from comparison using `n-i-1`
for (let j = 0; j < n - i - 1; j++) {
// Compare the adjacent elements
// If the first element is smaller than the second element then swap
if (arr[j] < arr[j + 1]) { // Note the change from > to <
// Swap arr[j] and arr[j+1] using a temporary variable
let temp = arr[j]; // Store the value of arr[j] in temp
arr[j] = arr[j + 1]; // Assign the value of arr[j+1] to arr[j]
arr[j + 1] = temp; // Assign the value of temp (originally arr[j]) to arr[j+1]
}
}
}
return arr; // return the sorted array
}
// Example of using bubble sort on an array of numbers
let arr = [64, 34, 25, 12, 22, 11, 90];
let sortedArr = bubbleSortDescending(arr); // calling the bubbleSortDescending method on the array of numbers
console.log("Sorted array is:", sortedArr);
// Output: Sorted array is: [90, 64, 34, 25, 22, 12, 11]
In this descending order implementation, the only change is in the if
condition within the inner loop:
- We now check if
arr[j] < arr[j+1]
instead ofarr[j] > arr[j+1]
. - This ensures that larger elements “bubble” to the beginning of the array with each pass.
Optimized Bubble Sort
We can optimize bubble sort to stop early if no swaps occur during a pass, indicating that the array is already sorted. This can significantly improve performance on nearly sorted data.
function optimizedBubbleSort(arr) {
// `arr` is the array that we want to sort
let n = arr.length; // Get the length of the array
// The outer loop goes through each element in the array
// After each pass, the largest unsorted element is placed at the end
for (let i = 0; i < n - 1; i++) {
// Initialize a flag to check if any swaps occurred in this pass
let swapped = false;
// The inner loop compares each adjacent element and swaps them if needed
// As the largest element is bubbled to end with each outer loop, we exclude the sorted elements from comparison using `n-i-1`
for (let j = 0; j < n - i - 1; j++) {
// Compare the adjacent elements
// If the first element is larger than the second element then swap
if (arr[j] > arr[j + 1]) {
// Swap arr[j] and arr[j+1] using a temporary variable
let temp = arr[j]; // Store the value of arr[j] in temp
arr[j] = arr[j + 1]; // Assign the value of arr[j+1] to arr[j]
arr[j + 1] = temp; // Assign the value of temp (originally arr[j]) to arr[j+1]
swapped = true;
}
}
// If no two elements were swapped in the inner loop, the array is sorted
if (swapped === false) {
break;
}
}
return arr; // return the sorted array
}
// Example of using bubble sort on an array of numbers
let arr = [64, 34, 25, 12, 22, 11, 90];
let sortedArr = optimizedBubbleSort(arr); // calling the optimizedBubbleSort method on the array of numbers
console.log("Sorted array is:", sortedArr);
// Output: Sorted array is: [11, 12, 22, 25, 34, 64, 90]
In this optimized implementation:
- We introduce a boolean variable
swapped
and set it tofalse
at the beginning of each pass (outer loop). - If we make any swaps during the inner loop, we set
swapped
totrue
. - After each pass, we check if
swapped
is stillfalse
. If it is, then we know that no swaps were made during that pass, which means the array is already sorted, and we can break out of the outer loop using thebreak
statement.
Sorting with Custom Comparison Function
To sort arrays of custom data types or objects, we can use a custom comparison function. This allows us to define our own sorting criteria.
function bubbleSortCustom(arr, compareFunc) {
// `arr` is the array that we want to sort
// `compareFunc` is a function that defines how to compare two elements
let n = arr.length; // Get the length of the array
// The outer loop goes through each element in the array
// After each pass, the largest unsorted element is placed at the end
for (let i = 0; i < n - 1; i++) {
// The inner loop compares each adjacent element and swaps them if needed
// As the largest element is bubbled to end with each outer loop, we exclude the sorted elements from comparison using `n-i-1`
for (let j = 0; j < n - i - 1; j++) {
// Compare the adjacent elements using the custom comparison function
if (compareFunc(arr[j], arr[j + 1]) > 0) {
// Swap arr[j] and arr[j+1] using a temporary variable
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr; // return the sorted array
}
// Example of using bubble sort on a list of custom objects
let people = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
{ name: "Charlie", age: 35 },
{ name: "David", age: 20 }
];
// Define a custom comparison function to sort by age
function compareByAge(person1, person2) {
// Compare the ages of two person
return person1.age - person2.age;
}
let sortedPeople = bubbleSortCustom(people, compareByAge);
console.log("Sorted list of people by age:", sortedPeople);
// Output:
// Sorted list of people by age:
// [
// { name: "David", age: 20 },
// { name: "Bob", age: 25 },
// { name: "Alice", age: 30 },
// { name: "Charlie", age: 35 }
// ]
In this custom object sorting implementation:
- We define a function
bubbleSortCustom(arr, compareFunc)
that takes an arrayarr
and a comparison functioncompareFunc
as input. - The
compareFunc
is a function that takes two elements from the array and returns:- A positive value if the first element should come after the second element.
- A negative value if the first element should come before the second element.
- Zero if the two elements are equal.
- We create an array of objects called
people
. - We define a custom comparison function
compareByAge(person1, person2)
that compares two objects based on theirage
property. - We call
bubbleSortCustom(people, compareByAge)
to sort the array of objects by age.
What’s Next?
Now that you’ve mastered the implementation of bubble sort in JavaScript, you might want to deepen your understanding with these related topics:
- Study the time and space complexity analysis to understand performance characteristics.
- Understand the Advantages and Disadvantages of Bubble Sort Algorithm.
- Learn about common mistakes and how to avoid them
- Compare it with other sorting algorithms to know when to use bubble sort.