Skip to content

Instantly share code, notes, and snippets.

@fortunee
Last active March 14, 2023 01:27
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 fortunee/b417d96b31c03ea20f8e0f941d14cf8d to your computer and use it in GitHub Desktop.
Save fortunee/b417d96b31c03ea20f8e0f941d14cf8d to your computer and use it in GitHub Desktop.
Bubble sort basically compares each element in the array and swaps them by moving the larger value towards the end of the array
/**
* PSEUDOCODE
* - start a loop that goes from the end to the start of the array;
* - start a second nested loop that goes from the start to the item below the
* - current position of the first loop;
* - compare each item with next item in the array
* - if current item is greater than the next item following it
* - then swap current item with next item
* - check if any swap happend at every complete iteration of the second loop
* - if no swaps happend then break out of the outer loop cos array has been sorted
* - return the sorted array
*/
function bubbleSort(array) {
let swapped;
for (let i = array.length; i > 0; i--) {
swapped = false;
for (let j = 0; j < i - 1; j++) {
if (array[j] > array[j+1]) {
// swap
let temp = array[j+1];
array[j+1] = array[j];
array[j] = temp;
swapped = true;
}
}
if (!swapped) {
break;
}
}
return array;
}
bubbleSort([8, 32, 5, 32, 3, 100, 11])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment