Skip to content

Instantly share code, notes, and snippets.

@roeib
Last active November 5, 2020 09:42
Show Gist options
  • Save roeib/6936264075ad1f98d136c6f637938066 to your computer and use it in GitHub Desktop.
Save roeib/6936264075ad1f98d136c6f637938066 to your computer and use it in GitHub Desktop.
function bubbleSort(inputArr) {
let n = inputArr.length;
let sorted = false;
let numOfIterations = 0;
while(!sorted) {
sorted = true;
for(let i = 0; i < n-numOfIterations+1; i++){
if(inputArr[i] > inputArr[i+1]){
let t = inputArr[i];
inputArr[i] = inputArr[i+1];
inputArr[i+1] = t;
sorted = false;
numOfIterations++;
}
}
}
return inputArr;
}
let inputArr = [5,1,4,2,8];
bubbleSort(inputArr);
console.log(inputArr); //[1, 2, 4, 5, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment