Improving the Quick sort

前端 未结 14 1323
终归单人心
终归单人心 2021-02-05 22:33

If possible, how can I improve the following quick sort(performance wise). Any suggestions?

void main()
    {
      quick(a,0,n-1);
    }

    void quick(i         


        
14条回答
  •  遥遥无期
    2021-02-05 23:05

    The first suggestion would be: replace one of the recursive calls with iteration. And I mean real iteration, not a manually implemented stack for recursion. I.e. instead of making two "new" calls to quick from quick, "recycle" your current call to quick to process one branch of recursion, and call quick recursively to process another branch.

    Now, if you make sure that you always make real recursive call for the shorter partition (and use iteration for the longer one), it will guarantee that the depth of recursion will never exceed log N even in the worst case, i.e. regardless of how well you choose your median.

    This all is implemented in qsort algorithm that comes with GCC standard library. Take a look at the source, it should be useful.

    Roughly, a more practical implementation that follows the above suggestion might look as follows

    void quick(int a[], int lower, int upper)
    {
      while (lower < upper)
      {
        int loc = partition(a, lower, upper);
        if (loc - lower < upper - loc)
        { /* Lower part is shorter... */
          quick(a, lower, loc - 1); /* ...process it recursively... */
          lower = loc + 1; /* ...and process the upper part on the next iteration */
        }
        else
        { /* Upper part is shorter... */
          quick(a, loc + 1, upper); /* ...process it recursively... */
          upper = loc - 1; /* ...and process the lower part on the next iteration */
        }
      }
    }
    

    This is just a sketch of the idea, of course. Not tested. Again, take a look at GCC implementation for the same idea. They also replace the remaining recursive call with "manual" recursion, but it is not really necessary.

提交回复
热议问题