Created
July 21, 2016 07:45
-
-
Save simshanith/d8a709631f010ded13c39a9ef76acfa1 to your computer and use it in GitHub Desktop.
paragonica challenges
This file contains 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
// http://www.paragonica.com/ | |
// --- | |
// # Bubble Sort One | |
/* | |
Bubble sort algorithms repeatedly step through a list of items to be sorted. Adjacent items are compared and swapped if they are in the wrong order. You repeat going through the list until no swaps are needed, indicating the list is sorted. Bubble sort is named for the way elements 'bubble' to the top of the list. | |
Challenge - create a function that takes an array as a parameter and performs a bubble sort to sort the following array of fruits in alphabetical order: | |
[ 'grape', 'banana', 'apple', 'orange', 'apricot', 'kiwi', 'strawberry'] | |
*/ | |
function bubbleSortOne(fruits) { | |
var needsNextPass = false; | |
fruits.forEach(function(fruit, i, fruits) { | |
if (i === fruits.length - 1) {return;} | |
if (fruits[i] < fruits[i+1]) {return;} | |
fruits[i] = fruits[i + 1]; | |
fruits[i+1] = fruit; | |
needsNextPass = true; | |
}); | |
if (needsNextPass) { return bubbleSortOne(fruits); } | |
return fruits; | |
} | |
bubbleSortOne([ 'grape', 'banana', 'apple', 'orange', 'apricot', 'kiwi', 'strawberry']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment