Skip to content

Instantly share code, notes, and snippets.

@CraigRodrigues
Last active October 17, 2019 11:28
Show Gist options
  • Save CraigRodrigues/c646c015a9ecc9e18d5c555eb972acaf to your computer and use it in GitHub Desktop.
Save CraigRodrigues/c646c015a9ecc9e18d5c555eb972acaf to your computer and use it in GitHub Desktop.
Bubble Sort in Javascript
// Normal
const bubbleSort = function(array) {
let swaps;
do {
swaps = false;
for (let i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
swaps = true;
}
}
} while (swaps);
return array;
};
// Recursively
const bubbleSort = function (array, pointer = array.length - 1) {
// Base Case
if (pointer === 0) {
return array;
}
for (let i = 0; i < pointer; i++) {
if (array[i] > array[i + 1]) {
let temp = array[i + 1];
array[i + 1] = array[i];
array[i] = temp;
}
}
// Recursive call on smaller portion of the array
return bubbleSort(array, pointer - 1);
};
@devreapr
Copy link

devreapr commented Oct 17, 2019

@luckyguy73 try this

function bubbleSort(list){
  let swapped=false;
    list.forEach((item,index)=>{
    if(item>list[index+1]){
      [list[index],list[index+1]] = [list[index+1],list[index]];
      swapped=true;
    }
  });
  if(swapped){
    return bubbleSort(list);
  }
  return list;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment