11/12测试用例,具有辅助功能的Quicksort

时间:2013-09-13 21:50:21

标签: c

这是未通过的测试用例:

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),除了这个测试用例,我还有EVEYRTHING工作。我一直在尝试将这个bug弄出来好几个小时,但我失败了。我曾尝试使用GDB来跟踪我的值,但在确定此错误时没有运气。任何人都可以提供任何意见吗?

首先运行sort函数,然后搜索帮助器是递归的并利用交换函数。

3 个答案:

答案 0 :(得分:3)

提示:运行代码时,您将从递归调用sorthelper的第二行到达此类调用。

sorthelper([0, 1, 5, 8, 7], 3, 4)

虽然它应该对8和7进行排序,但它没有做任何事情。想想为什么并修复它;)

答案 1 :(得分:2)

在sorthelper()函数中,当数组只有两个元素时,您正在跳过这种情况。请进行以下更改:

if (ind2 - ind1 <= 1) 

if (ind2 - ind1 < 1)

如果没有这个更改,包含偶数两个元素数组的测试用例会给你一个错误:(8,7)!

答案 2 :(得分:1)

两个问题。

  1. 您假设如果ind2 - ind1 == 1,则元素已经排序。这不是真的。这就是[8,7]分区最终没有排序的原因。
  2. 分区时,您将下部分区设置为从范围的开头到枢轴元素(w-1)。它应该转到枢轴之前的最后一个元素(w-2)。