0

As I understood QuickSort, it's all about creating subarrays of values and then combining them recursively in order to sort the array. I also know that the pivot element can be chosen in different ways, but the best one is when it's randomised (as it can achieve better algorithmic complexity in certain occasions). And, I could go on and on (I guess I am eager to learn more about the theoretic background).

Is this properly done QuickSort algorithm? Does it have any drawbacks which I should be aware of? And, though I have coded this piece on my own, I stole the idea for using the three dot operator (...). Could someone explain to me as to what does it exactly do? (I know kind of foolish of me to apply something that I'm not exactly certain of what it does).

function quickSort(array, beginning, end){
  if(beginning == undefined || end == undefined){
    beginning = 0;
    end = array.length - 1;
  }
  if(array.length <= 1){
    return array;
  }
  let random = Math.floor(Math.random() * array.length);
  let leftSubArray = [];
  let rightSubArray = [];
  let pivots = []
  for(let i = beginning; i <= end; i++){
    if(array[i] < array[random]){
        leftSubArray.push(array[i]);
    }else if(array[i] > array[random]){
        rightSubArray.push(array[i]);
    }else{
        pivots.push(array[i]);
    }
  }
  return [...quickSort(leftSubArray), ...pivots, ...quickSort(rightSubArray)];
}

let unsortedArray = [8,2,1,5,3,9,6,10,7,4];

let sortedArray = quickSort(unsortedArray);
console.log(sortedArray);
pilchard
  • 12,414
  • 5
  • 11
  • 23
Nenad
  • 1
  • duplicate [JavaScript quicksort](https://stackoverflow.com/questions/5185864/javascript-quicksort). also see: [Spread syntax (...)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) and [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – pilchard Apr 16 '23 at 10:06
  • possibly a better fit for [codereview](https://codereview.stackexchange.com/) – pilchard Apr 16 '23 at 10:06

0 Answers0