Help implementing quick sort [closed]
This is what I have and it doesn't work. Can't figure out why... The problem is probably in the quick_sort function.
#include <stdio.h>
#include <stdlib.h>
void quick_sort(int * a, int l, int r);
void swap(int * a, int i, int j);
int main(void)
{
#define N 10
int a[N], i;
for (i = 0; i < N; ++i) {
a[i] = rand();
printf("%d\n", a[i]);
}
quick_sort(a, 0, N - 1);
for (i = 0; i < N; ++i)
printf("%d\n", a[i]);
return 0;
#undef N
}
void quick_sort(int * a, int l, int r)
{
int i, j;
if (l < r) {
swap(a, rand() % (r - l + 1), r);
i = l;
for (j = l; j < r; ++j)
if (a[j] < a[r]) {
swap(a, i, j);
++i;
}
swap(a, i, r);
quick_开发者_开发百科sort(a, l, i - 1);
quick_sort(a, i + 1, r);
}
}
void swap(int * a, int i, int j)
{
int k;
k = a[i];
a[i] = a[j];
a[j] = k;
}
Fix this line: swap(a, rand() % (r - l + 1), r);
Should be: swap(a, l + rand() % (r - l + 1), r);
精彩评论