1

Does the QuickSelect algorithm work with duplicate values?

If I haven an Array

int[] array = {9, 8, 7, 6, 6, 6, 5, 0, 1, 2, 3, 4, 5, 5, 7, 200};

Will it be able to get the kth smallest element even though there are duplicates?

  • 1
    Yes it will work, and return the same value for a range of K's. –  Nov 10 '18 at 10:09
  • Can you please explain it in more detail? We say that if we pick a pivot at for example the mid, then we do partioning and if k is less than pivot, we only have to look through the left subarray. So now we know the kth element must be in the area k-1 which is the left part. But if there are duplicate values you can't say k-1 values? –  Nov 10 '18 at 10:19
  • In the partition process, you must make sure that none of the two subarrays ends up being empty. This guarantees that in the end there will be just one element left. –  Nov 10 '18 at 11:01

1 Answers1

1

Yes, it works. By the end of every iteration you have all elements less than current pivot stored to the left of the pivot.

Let's consider case when all elements are the same. In this case every iteration ends up putting pivot element to the left of the array. And the next iteration will continue with one element shorter array. So we need k iterations to find k-th smallest element.

Yola
  • 18,496
  • 11
  • 65
  • 106
  • @mth1417 Yes, quickselect is very similar to quicksort, you just continue to the right of to the left unlike quicksort where you go both directions. – Yola Nov 10 '18 at 10:31
  • @mth1417 Quicksort is very widely used sorting technique in the World, probably the most used one. That wouldn't be so it doesn't work with arrays with duplicates. – Yola Nov 10 '18 at 10:34