c - 正确划分快速排序数组

标签 c arrays recursion quicksort sub-array

我是 C 语言的初学者,我一直在尝试编写一个快速排序程序,该程序可以将随机生成的实数数组及其大小作为参数,然后按升序对元素进行排序。我无法弄清楚在函数 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;
}

最佳答案

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

A[i]=something;

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

#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;
} 

关于c - 正确划分快速排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40207088/

相关文章:

c - 零线程进程?

c - qsort() 使用哪种排序算法?

javascript - 如何从工作表计算谷歌应用程序脚本的持续时间?

python - 如何在 NumPy 中声明和填充数组?

java - 将整数编码为字节字符串

c - 8 回溯难题

c++ - 使用以 vector 为输入的递归方法时的段错误

c - 打开套接字时出错 : Success

algorithm - 合并排序的递归与时间复杂度

从二叉树创建链表(前序遍历)