Skip to content

Instantly share code, notes, and snippets.

@AtienoObwanda
Forked from Vinge1718/bubblesort.txt
Created March 17, 2022 05:37
Show Gist options
  • Save AtienoObwanda/ae4d2a440bf082abb7e27ed6c9a8f1cb to your computer and use it in GitHub Desktop.
Save AtienoObwanda/ae4d2a440bf082abb7e27ed6c9a8f1cb to your computer and use it in GitHub Desktop.
// Pseudocode
- As always we'll start by defining our function which takes an array as a parameter - as reviewed in the logic above: function bubbleSort(array){};
- Model the parent loop to iterate upto n-1 limits
- Model the inner loop to deduct each pass from the already set limit of the parent loop
- As we loop through the array we are going to be comparing and switching our array elements - when necessary, that is, until our largest number bubbles up to the top/end.
- With the two loops in place, we now need to build out the code to compare and switch neighbouring numbers - if necessary.
// Code
function bubbleSort(array){
for(var i = array.length; i > 0 ; i--){
for (var j = 0; j < i; j++){
if (array[j] > array[j+1]){
var temporaryVariable = array[j];
array[j] = array[j+1];
array[j+1] = temporaryVariable; // swap complete
}
}
}
return array;
}
//Test
bubbleSort([5,2,4,6,1,3]); //expect [ 1, 2, 3, 4, 5, 6 ]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment