Bubble Sort in JavaScript
October 13, 2023
Anonymous
Complete the following code:
```
// sort.js
function bubbleSort(array) {
```
ChatGPT
Certainly! Here's a complete implementation of the bubble sort algorithm in JavaScript:
javascript// sort.js
function bubbleSort(array) {
var len = array.length;
var swapped;
do {
swapped = false;
for (var i = 0; i < len - 1; i++) {
if (array[i] > array[i + 1]) {
// Swap the elements
var temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
} while (swapped);
return array;
}
// Example usage
var unsortedArray = [64, 34, 25, 12, 22, 11, 90];
var sortedArray = bubbleSort(unsortedArray);
console.log(sortedArray);
This code defines the bubbleSort
function that sorts an array using the bubble sort algorithm. The function repeatedly iterates through the array and swaps adjacent elements if they are in the wrong order until the entire array is sorted. The sorting process continues until no more swaps are needed.