Question & Examples
Start looping from with a variable called i from the end of the array towrads the beginning. Start an inner loop with a variable called j from the beginning until i - 1. If arr[j]
is greater than arr[j+1]
, swap those two values. Return the sorted array.
// Examples
bubbleSort([3, 6, 1, 34, 65, 26, 12, 53])
// [1, 3, 6, 12, 26, 34, 53, 65]
Implementation
function bubbleSort(arr) {
for (i = arr.length; i > 0; i--) { // 1
for (j = 0; j < i - 1; j++) { // 2
if (arr[j] > arr[j + 1]) { // 3
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]] // 4
}
}
}
return arr
}
- start a for loop. Set
i
toarr.length
so it starts from the end of the array. - start another for loop. Set
j
toi - 1
. We do this so we decrement the amount of times each pairs are being compared. - check to see if the element on the left is bigger than that on the right.
- If so, swap those elements
We can make this more intuitive by console logging some values
function bubbleSort(arr) {
for (i = arr.length; i > 0; i--) { // 1
for (j = 0; j < i - 1; j++) { // 2
console.log(arr, arr[j], arr[j+1])
if (arr[j] > arr[j + 1]) { // 3
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]] // 4
}
}
console.log("ONE LOOP FINISHED!")
}
return arr
}
console.log(bubbleSort([3, 6, 1, 34, 65, 26, 12, 53]))
// [3, 6, 1, 34, 65, 26, 12, 53] 3 6
// [3, 6, 1, 34, 65, 26, 12, 53] 6 1
// [3, 1, 6, 34, 65, 26, 12, 53] 6 34
// [3, 1, 6, 34, 65, 26, 12, 53] 34 65
// [3, 1, 6, 34, 65, 26, 12, 53] 65 26
// [3, 1, 6, 34, 26, 65, 12, 53] 65 12
// [3, 1, 6, 34, 26, 12, 65, 53] 65 53
// ONE LOOP FINISHED!
// [3, 1, 6, 34, 26, 12, 53, 65] 3 1
// [1, 3, 6, 34, 26, 12, 53, 65] 3 6
// [1, 3, 6, 34, 26, 12, 53, 65] 6 34
// [1, 3, 6, 34, 26, 12, 53, 65] 34 26
// [1, 3, 6, 26, 34, 12, 53, 65] 34 12
// [1, 3, 6, 26, 12, 34, 53, 65] 34 53
// ONE LOOP FINISHED!
// [1, 3, 6, 26, 12, 34, 53, 65] 1 3
// [1, 3, 6, 26, 12, 34, 53, 65] 3 6
// [1, 3, 6, 26, 12, 34, 53, 65] 6 26
// [1, 3, 6, 26, 12, 34, 53, 65] 26 12
// [1, 3, 6, 12, 26, 34, 53, 65] 26 34
// ONE LOOP FINISHED!
// [1, 3, 6, 12, 26, 34, 53, 65] 1 3
// [1, 3, 6, 12, 26, 34, 53, 65] 3 6
// [1, 3, 6, 12, 26, 34, 53, 65] 6 12
// [1, 3, 6, 12, 26, 34, 53, 65] 12 26
// ONE LOOP FINISHED!
// [1, 3, 6, 12, 26, 34, 53, 65] 1 3
// [1, 3, 6, 12, 26, 34, 53, 65] 3 6
// [1, 3, 6, 12, 26, 34, 53, 65] 6 12
// ONE LOOP FINISHED!
// [1, 3, 6, 12, 26, 34, 53, 65] 1 3
// [1, 3, 6, 12, 26, 34, 53, 65] 3 6
// ONE LOOP FINISHED!
// [1, 3, 6, 12, 26, 34, 53, 65] 1 3
// ONE LOOP FINISHED!
// [1, 3, 6, 12, 26, 34, 53, 65]
As we can see above, the number of times the pairs(arr[j]
and arr[j+1]
) are being compared decrements by one.