0

I used timothy roughgardens partition where he chooses the first element, but it doesn't quite work the way I want it to.

function swap(items, firstIndex, secondIndex){
  var temp = items[firstIndex];
  items[firstIndex] = items[secondIndex];
  items[secondIndex] = temp;
}


function partition(arr, left, right) {
  left = left || 0;
  right = right || arr.length - 1;
  var pivot = arr[0];
  var i = left + 1;
  for (var j = left + 1; j < right; j++) {
    if (arr[j] < pivot) { 
      swap(arr, j, i);  //need to swap with left most array entry which is currently bigger than pivot
      i++;
    }
  }
  //swap pivot with right most element smaller than the pivot (i-1)
  swap(arr, left, i-1)
  // console.log(arr);
  // return i;
  return i - 1;
}



function quickSort(arr, start, end) { 
  start = start || 0;
  end = end || arr.length - 1;

  var pivotNewIndex = partition(arr, start, end);

  if (start < end) {
    quickSort(arr, start, pivotNewIndex - 1);
    quickSort(arr, pivotNewIndex + 1, end);
  }
  return arr;
}


var arr4 = [3, 8, 2, 1, 5];


console.log(quickSort(arr4)); --- > [ 1, 2, 3, 8, 5 ];

what am I doing wrong here? I think end is getting reassigned from the original end, how do i stop that

1 Answer 1

1

You choose the first element of the whole array as pivot of working range here:
var pivot = arr[0];
But have to use the first element of current segment
var pivot = arr[left];

And check and debug your partition cycle. You must have two pointers, one walking from the left end and another from the right end of segment. But I see both walk from left to right (don't know JS enough to correct this issue)

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

2 Comments

I changed that and I still get [1, 2, 3, 8, 5]
Another thoughts added

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.