• Theory
  • Theory

Bubble Sort

Welcome to the first chapter of the sorting algorithms course! Here, you will learn about bubble sort and put this algorithm into practice.

How to Complete This Chapter

  1. Check out this interactive tutorial on bubble sort.
  2. Come back and complete this practice task to track your progress.
  3. Sharpen your skills with variable practice.

Your Task

Fix the sorting function so that the states of the array during sorting match the sample. You need to add the code that swaps the array elements.

To view the sample or test your program, click the button Boss, here’s your program!

Solution

The solution to the challenge will be available in a few minutes. Use it if you encounter difficulties. In the meantime, try to complete the challenge on your own.

let arr = [4, 6, 8, 1, 7];
draw(arr);
bubbleSort(arr);

function bubbleSort(arr) {
  let n = arr.length - 1;

  for (let pass = 0; pass < n; pass++) {
    for (let j = 0; j < n - pass; j++) {
      if (arr[j] > arr[j + 1]) {
        let temp = arr[j];
        arr[j] = arr[j + 1];
        arr[j + 1] = temp;
        draw(arr, j, j + 1);
      }
    }
  }
}
  • index.html
HTML
HTML

You’ve gone to a different page

Click inside the mini-browser to shift the focus onto this window.

100%
Granny Muffin

Easy there, pal!

To access the Bubble sort challenges in the Sorting Algorithms Made Visual, you need to sign up and subscribe first.