general formula for bubble sort in javascript code example
Example 1: how to do bubble sort in javascript
function BubbleSort(arr) {
const sortedArray = Array.from(arr);
let swap;
do {
swap = false;
for (let i = 1; i < sortedArray.length; ++i) {
if (sortedArray[i - 1] > sortedArray[i]) {
[sortedArray[i], sortedArray[i - 1]] = [sortedArray[i - 1], sortedArray[i]];
swap = true;
}
}
} while (swap)
return sortedArray;
}
console.log(BubbleSort([7,99,1,88,34,2,90,7]));
Example 2: bubble sort javascript
function bubbleSort(array) {
const len = array.length;
const retArray = array;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len - i; j++) {
const a = array[j];
if (a !== array[-1]) {
const b = array[j + 1];
if (a > b) {
retArray[j] = b;
retArray[j + 1] = a;
}
}
}
}
return retArray;
}
bubbleSort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);