正确分区QuickSort数组

时间:2016-10-23 19:43:20

标签: c arrays recursion quicksort sub-array

我是C的初学者,我一直在尝试编写一个Quicksort程序,可以将随机生成的实数数组及其大小作为参数,然后按升序对元素进行排序。我无法弄清楚在函数QuickSort的第一次递归调用中放入数组大小字段的内容,这意味着代表子数组A [0 ... q-1]。据我所知,其余的代码很好,因为当链接到生成随机数的驱动程序时,程序返回元素,尽管顺序不正确。我感谢任何帮助/建议。

int Partition(float *,int);

int QuickSort(float *A,int n)
{
  int q;

  if(n>1){
    q = Partition(A,n);
    QuickSort(&A[],q); //Trying to figure out what to put in here.
    QuickSort(&A[q+1],(n-1)-q); //This recursion sends the subarray A[q+1...n-1] to QuickSort, I think it works fine.
  }
}

int Partition(float *A,int n){
  int i,j;
  float x;

  x = A[n-1];
  i=0;
  for(j=0;j<=n-2;j++){
    if(A[j] <= x){
      A[i]=A[j];
      i = i+1;
    }
  }
  A[i]=A[n-1];
  return i;
}

1 个答案:

答案 0 :(得分:1)

你唯一的问题是你似乎感到困惑:

A[i]=something;

交换A[i]something。添加辅助tmp,或写一个交换函数:

#include<stdio.h>
int Partition(float *,int);

void QuickSort(float *A,int n) {
  int q;

  if(n>1){
    q = Partition(A,n);
    QuickSort(A,q); //Trying to figure out what to put in here.
    QuickSort(A+q+1,(n-q-1)); //This recursion sends the subarray A[q+1...n-1] to QuickSort, I think it works fine.
  }
}

int Partition(float *A,int n){
  int i,j;
  float x;
  float tmp;
  x = A[n-1];
  i=0;
  for(j=0;j<=n-2;j++){
    if(A[j] <= x){
      tmp = A[i];
      A[i]=A[j];
      A[j]=tmp;
      i = i+1;
    }
  }
  tmp = A[i];
  A[i]=A[n-1];
  A[n-1]=tmp;
  return i;
}

int main() {
    float A[] = {3, 4, -5, 10, 21, -9, -1, 7, 8, 10};
    QuickSort(A,10);
    for(int i = 0; i < 10; i ++)
        printf("%f ",A[i]);
    return 0;
}