I am working on implementing a bubble sort method in JavaScript, here is my current Code:
// Sort array (ascending)
function sort(array) {
var sortedArray = array;
// This swapped 'flag' tells the function whether or not it will
// need to iterate over the array again to continue sorting
var swapped = false;
for( var i = 1; i < array.length; i++ ) {
var prev = array[i - 1];
var current = array[i];
// If the previous number is > than the current, swap them around
if( prev > current ) {
swapped = true;
sortedArray[i] = prev;
sortedArray[i - 1] = current;
}
}
// If there has been a swap, sort over the array again
if( swapped ) {
return sort();
}
return sortedArray;
}
var testArray = [1, 4, 27, 3, 2];
// Run the sort function
sort(testArray); // [1, 2, 3, 4, 27]
When I run this, I keep getting ' cannot read property .length of undefined'
But, I can console.log(array.length) right before the for loop and it returns a value.
Here is a repl.it of my code.
Why am I getting an 'undefined'?
return sort(array)notreturn sort()?