Skip to content

Instantly share code, notes, and snippets.

@tcelovsky
Created October 26, 2021 20:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tcelovsky/8c2e8179ccd8d847e7c5af219960aff5 to your computer and use it in GitHub Desktop.
Save tcelovsky/8c2e8179ccd8d847e7c5af219960aff5 to your computer and use it in GitHub Desktop.
Optimized Bubble Sort Algorithm
function sortItems(array) {
for (let i = 0; i < array.length; i++) { // for loop iterates through each item in the array;
for (let j = 0; j < array.length; j++) { // for loop makes comparisons between each element in the array;
if (array[j] > array[j + 1]) { // if statement checks if the number on the left of a comparison is greater than the number on the right;
let temp = array[j]; // if it is, we swap the numbers; otherwise, do nothing.
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment