Can not complete Quick Sort algorithm

I fail to pass the third challenge :

" quickSort should return an array that is unchanged except for order."

in console my result looks as intended

Your code so far


function quickSort(array) {  
let l = array.length
if (l > 1) {
  let pivot = array[Math.floor(l/2)]
  let small = []
  let large = []    
  
  for (let i=1; i<l; i++) {
    if (array[i] <= pivot) {
      small.push(array[i])
    } else {
      large.push(array[i])
    }
  }; 
  // console.log(small, large, pivot)
  return quickSort(small).concat(pivot, quickSort(large))  
} else return array;  
}

// test array:
// [1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]
console.log(quickSort([1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92]))

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36.

Challenge: Implement Quick Sort

Link to the challenge:


This is what your function is returning. It should just be returning a single array.

Are you getting this answer? Because that’s indeed modified array

//[1, 4, 2, 8, 345, 123, 43, 32, 5643, 63, 123, 43, 2, 55, 1, 234, 92] input
//[1, 1, 2, 43, 43, 43, 55, 55, 63, 63, 92, 92, 123, 123, 234, 234, 5643] output

Notice that some elements are missing and some are more times than they were originally.

Consider two things - before quickSort is being called on the smaller arrays pivot element should be positioned between the two, but not included in them.
Does this apply to your function?

Second hint - are you sure that all other elements are split to small or large arrays? It looks like you might have changed the way you pick your pivot but didn’t make further changes to adapt to this change.

Ok the second hint did the trick, thanks! Just by changing let pivot = array[0] passes the test and yes the array is changed, some numbers are indeed missing and some are repeated. I did not notice at first used just .length and a quick look. Of course later on i will try to do it with my pivot point.

1 Like

appreciated but the problem was found elsewhere thanks!