【问题标题】:Properly Partitioning QuickSort Array正确分区快速排序数组
【发布时间】:2017-03-05 13:29:17
【问题描述】:

我是 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;
}

【问题讨论】:

  • 使用0作为缺失的下标。
  • 嗯,更接近了,子数组排序正确,但整个数组没有排序。所以看起来像: A[0] = 0.197551 A[1] = 0.277775 A[2] = 0.277775 A[3] = 0.277775 A[4] = 0.553970 A[5] = 0.197551 A[6] = 0.277775 A[7 ] = 0.277775 A[8] = 0.553970 A[9] = 0.553970
  • 如果添加基本的数组打印功能,可以在关键的地方调用,比如在入口和出口的Partition()。如果你这样做,你会发现你的分区代码完全搞砸了你的数组——之前和之后的内容是不一样的。比如我得到了P1 (5): [0] = 0.197551 [1] = 0.277775 [2] = 0.277775 [3] = 0.277775 [4] = 0.197551——P2 (5): [0] = 0.197551 [1] = 0.197551 [2] = 0.277775 [3] = 0.277775 [4] = 0.197551,其中下标[1]的值从0.277775变成了0.197551。您需要交换元素,而不仅仅是移动它们。

标签: c arrays recursion quicksort sub-array


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 2016-08-14
    • 1970-01-01
    • 2015-10-28
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多