1

I have a sub array that is {8,9,7}. Assume the pivot that was picked is 8. Running Quickselect on this array is giving me some issue. So the left pointer starts from the left looking for elements greater than 8 it finds 9. The right pointer starts from the right look for elements smaller than 8 it finds 7. 7 and 9 swap places. {8,7,9} now the left pointer finds 9 again and the right pointer finds 7. But now they have crossed each-other so we don't perform that swap. Instead the left pointer is swapped with the pivot creating the array {9,7,8} but this is not good since smaller elements are not to the left of the pivot now. So what did I do wrong?

johnnyB
  • 11
  • 2

1 Answers1

1

This is much later, so you no doubt already figured it out, but for posterity:

The first part of your description above matches the first partition step in QuickSelect (or QuickSort) using a zero index (value 8 here) as the pivot.

The {8,7,9} variation is correct - the two parts {8,7} and {9} meet the partition criterion for a pivot value of 8. These are then recursively processed to complete the sort, if sorting. Of course, if you're (quick)selecting, you only process the part that the index you seek is in.

The left pointer is swapped with the pivot step does not apply here. You should only do that if you use the variation where you move the pivot to the front or the back, if it's not already there, and then exclude the pivot index from the partitioning process. Only if you did that would the pivot value need to be moved to the where the two partitions meet.