这是未通过的测试用例:

5 0 1 8 7

这是我的密码。
void swap(int* A, int* B)
{
  int t;
  t = *A;
 *A = *B;
 *B=t;
 }

void sorthelper(int * arr,int ind1, int ind2)
{
  int r = ind1+1;
  int w = ind1+1;
  // int i = 0;

  if (ind2 - ind1 <= 1)
    {
      return;
    }

  for(r=ind1+1; r<=ind2;r++)//For r starting at one bigger then pivot and less then the length(ind2), increment r by one each time
     {
       if(arr[r] < arr[ind1])// if read is bigger then pivot, increment w and swap w and r
         {
           swap(&arr[w],&arr[r]);
           w++;
         }
     }
       swap(&arr[ind1], &arr[w-1]);//swap pivot with one less then write spot


       sorthelper(arr, ind1, w-1);
       sorthelper(arr, w ,ind2);

}


void sort(int * arr, int length)
{
  int ind1 = 0;
  int ind2 = 0;
  ind2 = length-1;
  sorthelper(arr, ind1, ind2);
  return;
}

我正在尝试编写一个快速排序算法(是的,这是hw),除了这个测试用例之外,我还有其他工作要做我已经试着解决这个问题好几个小时了,但我失败了我试过使用GDB来跟踪我的值,但是在确定这个错误时没有运气有人能提供意见吗?
排序函数首先运行,然后搜索助手是递归的,并使用交换函数。

最佳答案

在sorthelper()函数中,当数组只有两个元素时,将跳过此情况。请做以下更改:

if (ind2 - ind1 <= 1)


if (ind2 - ind1 < 1)

如果没有这个更改,一个甚至由两个元素数组组成的测试用例将给您一个错误:(8,7)!

关于c - 11/12测试用例,具有帮助功能的Quicksort,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18795807/

10-13 03:21