简体   繁体   English

算法-快速排序的实现问题

[英]algorithm - problems with implementation of quicksort

I am learning algorithms as a beginner.When learning quicksort,I found that there're several ways to implement the quick sort.So I choose this the way in this tutorial to implement quicksort. 我是一个初学者,正在学习算法。学习快速排序时,我发现有多种方法可以实现快速排序。因此,在本教程中 ,我选择这种方式来实现快速排序。

It chooses the element in end of the array as pivot,and choose the first element as a wall separating the values which are less and greater than the pivot.when the sort is done, insert the pivot in the position of wall and make partition. 它选择数组末尾的元素作为枢轴,并选择第一个元素作为分隔小于和大于枢轴的值的墙。完成排序后,将枢轴插入墙的位置并进行分隔。

Here's my implementation in c: 这是我在c中的实现:

void simpleqs(int* data,int start,int end)
{
 int wall = start;
 int pivot = data[end];

 //Base case
 if (start >= end)
 {
   return;
 }

 //Sort the array
 for(int e = start;e < end-1; e++)
 {
   if(data[e] < pivot)
   {
    swap(&data[e],&data[wall]);
    wall++;
   }
 }

 //Partition

 if(data[wall] >= pivot)
 {
   swap(&data[wall],&data[end]);
 }

 simpleqs(data,start,wall-1);
 simpleqs(data,wall+1,end);
 }

In main: 在主要方面:

int main(void)
{
  int dataSet[] = {2,4,1,5,6,9,8,3,7,10,20,13,11,17,15};

  int size = sizeof(dataSet)/sizeof(int);

  simpleqs(dataSet,0,size-1);

  for(int e = 0;e < size ; e++)
  {
    printf("%d,", dataSet[e]);
  }
  printf("\n");

}

There will always be one value in the wrong position,I can't figure out why. 错误的位置总会有一个值,我不知道为什么。

Like this: 像这样:

1,2,3,4,5,6,8,9,7,10,11,13,15,17,20,

Please help me to revise my logic,thanks! 谢谢,请帮助我修改我的逻辑!

You should go to the end, not end - 1. 您应该走到尽头,而不是走到尽头-1。

// Sort the array
for (int e = start; e < end; e++)
{
    if (data[e] < pivot)
    {
        swap(&data[e], &data[wall]);
        wall++;
    }
}

您已经实现了Lomuto分区 ,但是错过了对(end-1) -th元素的处理:

for(int e = start;e < end; e++)

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

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