简体   繁体   English

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

[英]11/12 Test cases, Quicksort with helper function

This is the test case that does not pass: 这是未通过的测试用例:

5 0 1 8 7

This is my code. 这是我的代码。

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

I am trying to write a quicksort algorithm (Yes, this is hw) and I have EVEYRTHING working except this test case. 我正在尝试编写一种快速排序算法(是的,这是硬件),并且除了该测试用例之外,我都可以使用EVEYRTHING。 I've been trying to work this bug out for hours but I have failed. 我一直在努力解决这个错误,但失败了。 I have tried using GDB to track my values but no luck in determining this error. 我曾尝试使用GDB来跟踪我的值,但在确定此错误方面没有走运。 Can anyone offer any input? 谁能提供任何意见?

the sort function gets run first, then the search helper is recursive and utilizes the swap function. 首先运行sort函数,然后搜索助手是递归的,并利用swap函数。

Hint: When running your code, you will reach a call like this from the second line of recursive call to sorthelper. 提示:在运行代码时,您将从第二行递归调用sorthelper到达这样的调用。

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

It doesn't do anything although it should sort the 8 and the 7. Think why and fix it ;) 尽管它应该对8和7进行排序,但是它什么也没做。

In your sorthelper() function, you are skipping the case when the array has only two elements. 在您的sorthelper()函数中,当数组只有两个元素时,您将跳过这种情况。 Please make the following change: 请进行以下更改:

if (ind2 - ind1 <= 1) 

to

if (ind2 - ind1 < 1)

Without this change, a test case consisting of even two element array would give you an error: (8,7)! 如果不进行此更改,那么即使由两个元素数组组成的测试用例也会给您一个错误:(8,7)!

Two problems. 两个问题。

  1. You assume that if ind2 - ind1 == 1, the elements are already sorted. 您假设如果ind2-ind1 == 1,则元素已经排序。 This is not true. 这不是真的。 This is why the [8, 7] partition doesn't end up sorted. 这就是[8,7]分区最终未排序的原因。
  2. When partitioning, you're setting up the lower partition to go from the start of the range to the pivot element (w-1). 进行分区时,您正在将下部分区设置为从范围的起点到枢纽元素(w-1)。 It should go to the last element BEFORE the pivot (w-2). 它应该转到枢轴(w-2)之前的最后一个元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM