Example 1: bubble sort javascript
bubbleSort(Array) {
let len = Array.length;
for (let i = 0; i < len; i++) {
for (let j = 0; j < len; j++) {
if (Array[j] > Array[j + 1]) {
let tmp = Array[j];
Array[j] = Array[j + 1];
Array[j + 1] = tmp;
}
}
}
return Array;
};
Example 2: javascript bubble sort
const bubbleSort = (arr) => {
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
let tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
}
}
}
return arr;
}
Example 3: javascript bubble sort
const bubbleSort = array => {
const arr = Array.from(array);
for (let i = 1; i < arr.length; i++) {
for (let j = 0; j < arr.length - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
};
console.log(bubbleSort([4, 9, 2, 1, 5]));
Example 4: python bubble sort
def bubbleSort(arr):
n = len(arr)
# Traverse through all array elements
for i in range(n-1):
# range(n) also work but outer loop will repeat one time more than needed.
# Last i elements are already in place
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
Example 5: boble sorting javascript
function bubbleSort(array) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array.length; j++) {
let item = array[j];
var nextItem = array[j + 1];
if (item > nextItem) {
array[j] = nextItem;
array[j + 1] = item;
}
}
}
return array;
}
console.log(bubbleSort([9, 5, 7, 1, 0, 2, 4, 10, 1, 6, 3, 5, 8]));
console.log(bubbleSort([900, 5, 70, 0.1, 0, 02, 4, 100, 1, 6, 35, 56, 8]));
Example 6: 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]));