void partition(int *a, int size) {
int pivot = a[0];
int left = 0, right = 0;
for(left = 1, right = size-1; left <= right; left++, right--) {
if(a[left] >= pivot && a[right] <= pivot){
swap(left, right, a);
}
}
swap(0, right, a);
}
I wrote this method to partition an array as a preliminary step in order to apply quick sort, I tested it on this sample data:
8 2 5 13 4 19 12 6 3 11 10 7 9
the correct output should be:
6 2 5 7 4 3 8 12 19 11 10 13 9
but the actual output is:
6 2 5 13 4 3 8 12 19 11 10 7 9
The algorithm has to swap 13 with 7 but it fails due to the && condition in the above loop. I want to increment left only if a[left] >= pivot and decrement right only if a[right]<= pivot.
std::partitionwould be the more appropriate reference.