Bubble sort accepts an array, and to note, this function mutates the incoming array. This can be overcome easily with a few modifications but lets keep it simple for now.
function bubbleSort(arr) { for (let i in arr) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } return arr } console.log(bubbleSort([5, 3, 8, 4, 2])) // [2, 3, 4, 5, 8]
Console:
Once in the function we arrive at the first of two for
loops. This first for
loop simply loops through the array, index by index.
function bubbleSort(arr) { // for (let i in arr) { for (let j = 0; j < arr.length - i - 1; j++) { // if (arr[j] > arr[j + 1]) { // let temp = arr[j] // arr[j] = arr[j + 1] // arr[j + 1] = temp // } } // } return arr }
Once we are in the first loop which loops through each item in the array, we now arrive at a slightly more complex . We start with a new let j
value set to 0, and while that is less than the current array length minus the current outer loop index minus 1 to zero base the value. Phew thats alot, but the way bubble sort works means that each outer iteration that occurs, we should expect the the the end of the array to be sorted. Meaning that after one iteration of the outer loop, the last index in the array would be sorted. After two iterations we would have 2 sorted items at the end of the array. So as the outer loop iterates, we need to run the inner loop less and less.
function bubbleSort(arr) { // for (let i in arr) { // for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { // let temp = arr[j] // arr[j] = arr[j + 1] // arr[j + 1] = temp } // } // } return arr }
Now as we are iterating through the loops, we run a comparison check to see if the current arr[j]
value is larger than the next value in the array. If it is smaller, that means the current value is in a good sorted order but if the current value is bigger than its neighbor that means that value is unsorted. .
function bubbleSort(arr) { // for (let i in arr) { // for (let j = 0; j < arr.length - i - 1; j++) { // if (arr[j] > arr[j + 1]) { let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp // } // } // } return arr }
To resolve this unsorted issue, we swap the two values. First we save the current value to a temporary variable. Next we assign the current array value to the value of the next array index. When then replace that next neighbors value with the temporary value we saved earlier.
function bubbleSort(arr) { for (let i in arr) { for (let j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let temp = arr[j] arr[j] = arr[j + 1] arr[j + 1] = temp } } } return arr }
So you can see all together, this small amount of code packs a big punch. Looping through the main array, while constantly doing smaller loops to reorder the current value. Altogether you get a simple but powerful learning tool to reinforce fundamentals. Now get out there and bubble sort some arrays!