I believe this Quicksort deployment approach is confusing and flawed, but it seems to work. I mean this pseudo code . Note : they also have a C implementation at the end of the article, but it is very different from their pseudo-code, so I don't care.
I also wrote this in C, like this, trying as much as possible to stay true to the pseudo-code, even if it means that you are doing some strange C stuff:
#include <stdio.h> int partition(int a[], int p, int r) { int x = a[p]; int i = p - 1; int j = r + 1; while (1) { do j = j - 1; while (!(a[j] <= x)); do i = i + 1; while (!(a[i] >= x)); if (i < j) { int t = a[i]; a[i] = a[j]; a[j] = t; } else { for (i = 1; i <= a[0]; ++i) printf("%d ", a[i]); printf("- %d\n", j); return j; } } } int main() { int a[100] = //{8, 6,10,13,15,8,3,2,12}; {7, 7, 6, 2, 3, 8, 4, 1}; partition(a, 1, a[0]); return 0; }
If you run this, you will get the following output:
1 6 2 3 4 8 7 - 5
However, this is wrong, isn't it? It is clear that a[5] does not have all the values before it is lower, since a[2] = 6 > a[5] = 4 . Not to mention that 7 must be rotary (initial a[p] ), and yet its position is incorrect and lost.
The following partition algorithm is taken from wikipedia :
int partition2(int a[], int p, int r) { int x = a[r]; int store = p; for (int i = p; i < r; ++i) { if (a[i] <= x) { int t = a[i]; a[i] = a[store]; a[store] = t; ++store; } } int t = a[r]; a[r] = a[store]; a[store] = t; for (int i = 1; i <= a[0]; ++i) printf("%d ", a[i]); printf("- %d\n", store); return store; }
And produces this conclusion:
1 6 2 3 8 4 7 - 1
What is the correct result, in my opinion: the axis ( a[r] = a[7] ) has reached the final position.
However, if I use the initial sectioning function in the following algorithm:
void Quicksort(int a[], int p, int r) { if (p < r) { int q = partition(a, p, r);
... this seems to be the correct sorting algorithm. I tested it on a variety of random inputs, including all 0-1 arrays of length 20.
I also tried using this separation function for a selection algorithm in which it was not able to get the correct results. It seems to work, and it even works very fast as part of a quick sort algorithm.
So my questions are:
- Can someone post an example where the algorithm does NOT work?
- If not, then why does it work, as part of the section seems wrong? Is this another separation approach that I don't know about?