-
-
Save tori-bot/b18600ff2dc42b80104b4765a6140134 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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