Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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