1

This is the quicksort algorithm I wrote:

var arr = [0, 2, 5, 10, 3, 22, 12, 8, 20];

let quickSort = (arr) => {
  let len = arr.length;

  if (len === 1) {
    return arr;
  };

  let pivot = arr.length - 1;

  const rightArr = [];
  const leftArr = [];

  for (let i = 0; i < len - 1; i++) {
    let j = i + 1;
    if (arr[j] > arr[pivot]) {
      rightArr.push(arr[j]);
    } else {
      leftArr.push(arr[j]);
    };
  };
  if (leftArr.length > 0 && rightArr.length > 0) {
    return [...quickSort(leftArr), pivot, ...quickSort(rightArr)];
  } else if (leftArr.length > 0 && rightArr.length <= 0) {
    return [...quickSort(leftArr), pivot];
  } else {
    return [pivot, ...quickSort(rightArr)];
  };
};

console.log(quickSort(arr));

The output is: [20, 1, 2, 3, 4, 5, 6, 8, 22]

My question is: why do I get the wrong output and how do I fix this ?

5
  • 2
    The for loop skips arr[0]. Commented Jul 25, 2021 at 12:11
  • 4
    fwiw, quicksort is supposed to sort an array in place. The posted function creates new sub-arrays by copying into new arrays, which real quicksort does not do. Commented Jul 25, 2021 at 12:16
  • 1
    There is much wrong with this code, but the problem arises from adding pivot to the list instead of arr[pivot], pivot being the index Commented Jul 25, 2021 at 12:20
  • thank you @Vulwsztyn i solved the problem and evreything work just fine. Commented Jul 25, 2021 at 12:28
  • Since I apparently resolved your issue I added my comment as answer. Would you mind accepting it? Commented Jul 25, 2021 at 12:46

1 Answer 1

2

There is much wrong with this code, but the problem arises from adding pivot to the list instead of arr[pivot], pivot being the index

Sign up to request clarification or add additional context in comments.

1 Comment

e.g.: all conditions at the end of code are redundant, why would you use semicolon in js? it's not real in-situ quicksort, for that you should be swaping elements of the array and not create additional ones

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.