Please can you tell me what is wrong to this implementation of bubble sort algorithm in JavaScript?
function bubbleSort(arr) {
var swapped;
do {
swapped = false;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped)
}
console.log(bubbleSort([4, 25, 1, 6, 2])); // [ 1, 2, 4, 6, 25 ]
console.log(bubbleSort([13, 1, 9, 38, 8, 3, 1])); // [ 1, 2, 4, 6, 25 ]
Your function will return undefined
.You need to return arr
from the function.
If you don't want to modify the original array then make a copy of original array using slice()
. In the below case it doesnot matter because arrays are not stored in any variable.
function bubbleSort(arr) {
arr = arr.slice()
var swapped;
do {
swapped = false;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
var temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
swapped = true;
}
}
} while (swapped)
return arr;
}
console.log(bubbleSort([4, 25, 1, 6, 2])); // [ 1, 2, 4, 6, 25 ]
console.log(bubbleSort([13, 1, 9, 38, 8, 3, 1])); // [ 1, 2, 4, 6, 25 ]