I have to implement an algorithm that returns the median of an array. So I chose to implement Quickselect which seems to be efficient for this and I saw that for the tripartition I can use the same partition algorithm used in Quicksort.
The partition algorithm reported in my lecture notes (in C code) is the following:
for (i = lo, j = hi;
(i <= j);)
{
while (a[i] < pivot)
{
i++;
}
while (a[j] > pivot)
{
j--;
}
if (i <= j)
{
if (i < j)
{
/* exchange values */
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
i++;
j--;
}
}
Now, if my array is: a = [40, 20, 100, 60, 80] and I choose as pivot the number 80, the result is: a = [40, 20, 80, 60, 100], but as you can see the values in the right partition are not all > 80 (we have 60). If I choose any other number the algorithm works properly.
Is this algorithm wrong?
Thank you for your help in advance!