Implement the Bubble Sort Algorithm - Implement the Bubble Sort Algorithm

Tell us what’s happening:

This code passes but i want to be sure if this is actually bubble sort.
I tried the same code in selection sort and it passed. I think labs only check if the array is sorted not what sorting algorithm we are using.

Your code so far

function bubbleSort(array) {
  for (let i = 0; i < array.length; i++) {
    if (array[i + 1] < array[i]) {
      let temp = array[i];
      array[i] = array[i + 1];
      array[i + 1] = temp;
    }
  }

  for (let i = 0; i < array.length; i++) {
    if (array[i + 1] < array[i]) {
      bubbleSort(array);
      break;
    }
  }
  return array
}

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36

Challenge Information:

Implement the Bubble Sort Algorithm - Implement the Bubble Sort Algorithm

GitHub Link: freeCodeCamp/curriculum/challenges/english/blocks/lab-bubble-sort-algorithm/698367b9d1c6914a22095aec.md at main · freeCodeCamp/freeCodeCamp · GitHub

I’ve changed the category of your topic to better reflect its content.

Hi @BHAT_AAQIB

The instructions do not mention recursion, so I’m not sure about your approach.

However, the two for loops are exactly the same, which is going against the DRY (don’t repeat yourself) principle.

Happy coding

Fixed that part.

function bubbleSort(array) {
  for (let i = 0; i < array.length; i++) {
    if (array[i + 1] < array[i]) {
      let temp = array[i];
      array[i] = array[i + 1];
      array[i + 1] = temp;
      bubbleSort(array);
      break;
    }
  }

  return array
}

console.log(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]))

And this is without recursion.

function bubbleSort(array) {
  for (let j = 0; j< array.length; j++) {
    for (let i = 0; i < array.length - 1; i++) {
    if (array[i + 1] < array[i]) {
      let temp = array[i];
      array[i] = array[i + 1];
      array[i + 1] = temp;
    }
   }
  }
  return array
}

console.log(bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]))