I'm having a really hard time with the implementation of Hoare's partition algorithm. Basically, what i want to do is split an array into two parts, the first one containing numbers lesser than the given x
, and the other one containing the greater. However, I just can't figure out a good implementation. This is my code:
void hoare(vector<int>&arr,int end, int pivot)
{
int i = 0;
int j = end;
while (i < j)
{
while (arr[i] < pivot)
i += 1;
while (arr[j] > pivot)
j -= 1;
swap(arr[i],arr[j]);
}
// return arr;
for (int i=0; i<end; i++)
printf("%d ", arr[i]);
}
Now I've found out that loads of sites have while (arr[i] <= pivot)
instead of what I put down there. However, when I do that, for an array like this:
1 3 5 7 9 2 4 6 8
I get:
1 3 5 4 9 2 7 6 8
But then again, in my version, for such a set:
12 78 4 55 4 3 12 1 0
the program freezes, because since neither condition in the outer loop is fulfilled, it just goes through it over and over again, without incrementing j
or i
.
The pivot is a pointer to a specific number in the array, counting from 1; for instance, number 3 passed to function in the first example would mean the pivot
equals arr[2]
, which is 5
Sorry if that's a noob question or has already been answered, but I've spent the whole day on this (also searching the net for a solution) to no avail and now I'm having suicidal thoughts.
Thanks in advance.