bubble short js 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: buble sort in js
let bubbleSort = (inputArr) => { let len = inputArr.length; for (let i = 0; i < len; i++) { for (let j = 0; j < len; j++) { if (inputArr[j] > inputArr[j + 1]) { let tmp = inputArr[j]; inputArr[j] = inputArr[j + 1]; inputArr[j + 1] = tmp; } } } return inputArr;};