0

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'?

2
  • 6
    return sort(array) not return sort()? Commented Mar 31, 2014 at 14:11
  • Thanks Andy, that's it! I think I need my Monday morning coffee before attempting anything else. Thanks again! Commented Mar 31, 2014 at 14:13

2 Answers 2

2

As per my comment: you need to pass in array to the sort function again:

if (swapped) {
  return sort(array);
}
Sign up to request clarification or add additional context in comments.

Comments

0
 // If there has been a swap, sort over the array again
  if( swapped ) {
    return sort();
  }

You are returning sort() with no argument here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.