开发者

Help implementing quick sort [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center. Closed 11 years ago.

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);

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜