This is my quicksort algorithm, including partition and swap. Works well, when I'm choosing as a pivot the last element of the array (in function quicksort: int r = partition(a, n, n);
), but fails when taking the first: int r = partition(a, n, s);
void Swap(int a[], int l, int r){
int tmp = a[l];
a[l] = a[r];
a[r] = tmp;
}
int partition(int a[], int n, int p) {
Swap(a, p, n);
int l = 0;
for (int i = 1; i <= n - 1; i++) {
if (a[i] <= a[n]) {
l += 1;
Swap(a, l, i);
}
}
Swap(a, p, l + 1);
return l + 1;
}
void quicksort(int a[], int s, int n) {
if (s < n) {
int r = partition(a, n, n);
quicksort(a, s, r - 1);
quicksort(a, r + 1, n);
}
}
a[0]
) - Yksisarvinenp
to indexn
at the beginning ofpartition()
, you need to swap it fromn
into its final position at the end. Instead, you swap whatever element then happens to be at indexp
into the pivot position, which is correct only ifn == p
. - John Bollinger