简体   繁体   English

Quicksort混乱

[英]Quicksort confusion

I'm going through the quicksort and whichever article i see, i get more confused. 我正在浏览快速排序,无论我看到哪一篇文章,我都会感到困惑。

1) This implementation is really good http://gauss.ececs.uc.edu/Courses/C321/html/quicksort.java.html 1)这个实现非常好http://gauss.ececs.uc.edu/Courses/C321/html/quicksort.java.html

But as i understand, after each pass, the pivot index is in correct position. 但据我所知,每次通过后,枢轴指数处于正确的位置。

Then ideally we should be doing the following: 理想情况下,我们应该做以下事情:

   public static void Quicksort(int A[], int f, int l)
   {
      if (f >= l) return;
      int pivot_index = partition(A, f, l);
      Quicksort(A, f, pivot_index-1); //*** pivot_index-1
      Quicksort(A, pivot_index+1, l);
   }

But tutorial uses Quicksort(A, f, pivot_index); 但是教程使用Quicksort(A,f,pivot_index); .

I'm 200% sure that making the change 'pivot_index-1' will not improve any performance or reduce the complexity; 我百分之百地确保进行更改'pivot_index-1'不会改善任何性能或降低复杂性; but just want to make if my understanding is correct. 但是如果我的理解是正确的,那就是想做。

2) The implementation here works; 2) 这里的实施有效; but it doesn't place the pivot element at the correct position with each pass. 但是每次通过时它都不会将枢轴元件放在正确的位置。

Two implementations I've seen: 我见过的两个实现:

  • End index inclusive 结束指数包括在内
  • End index exclusive 结束索引独占

Quicksort(A, f, pivot_index-1); is for the first case. 是第一种情况。

Quicksort(A, f, pivot_index); is for the second case. 是第二种情况。

Doing Quicksort(A, f, pivot_index); Quicksort(A, f, pivot_index); on the first case will still result in a sorted list, but will do a bit of extra work. 在第一种情况下仍然会产生一个排序列表,但会做一些额外的工作。

Doing Quicksort(A, f, pivot_index-1); Quicksort(A, f, pivot_index-1); on the second case probably won't result in a fully sorted list all the time. 在第二种情况下可能不会一直导致完全排序的列表。

Analysis of this implementation : 分析这个实现

I can see why it works (it will swap the pivot with a greater element at a lower index), but that's not the QuickSort I know, and it might be doing slightly more work than required. 我可以看到它为什么有效(它将在较低的索引处用更大的元素交换枢轴),但这不是我所知道的QuickSort,它可能比所需的工作略多一些。

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

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