Quick Sort

Properties

  • Not stable
  • O(lg(n)) extra space (see discussion)
  • O(n2) time, but typically O(n·lg(n)) time
  • Not adaptive

Discussion

When carefully implemented, quick sort is robust and has low overhead. When a stable sort is not needed, quick sort is an excellent general-purpose sort -- although the 3-way partitioning version should always be used instead.
The 2-way partitioning code shown above is written for clarity rather than optimal performance; it exhibits poor locality, and, critically, exhibits O(n2) time when there are few unique keys. A more efficient and robust 2-way partitioning method is given in Quicksort is Optimal by Robert Sedgewick and Jon Bentley. The robust partitioning produces balanced recursion when there are many values equal to the pivot, yielding probabilistic guarantees of O(n·lg(n)) time and O(lg(n)) space for all inputs.
With both sub-sorts performed recursively, quick sort requires O(n) extra space for the recursion stack in the worst case when recursion is not balanced. This is exceedingly unlikely to occur, but it can be avoided by sorting the smaller sub-array recursively first; the second sub-array sort is a tail recursive call, which may be done with iteration instead. With this optimization, the algorithm uses O(lg(n)) extra space in the worst case.

Program C Code

//Quick sort
void quicksort(int gelendizi[],int sol, int sag)
{
    int solindex,sagindex, orta,temp,i;

    solindex=sol;
    sagindex=sag;
    orta=gelendizi[(sol+sag)/2];
    do
    {
        while (gelendizi[solindex]<orta && solindex<sag)//pivotun solunda, pivottan buyuk ilk elemana ulasilincaya kadar
            solindex++;
        while (orta<gelendizi[sagindex] && sagindex>sol)//pivotun saginda, pivottan kucuk ilk elemana ulasilincaya kadar
            sagindex--;
        if (solindex<=sagindex)  //pivotun sag ve solundaki elemanlari yer degistir
        {
            temp=gelendizi[solindex];
            gelendizi[solindex]=gelendizi[sagindex];
            gelendizi[sagindex]=temp;
            solindex++;
            sagindex--;
            printf("\n");
            for (i=0;i<8;i++)
                printf("%d, ", gelendizi[i]);
                printf("\n");
        }
    }
    while (solindex<=sagindex);

    if (sol < sagindex) quicksort(gelendizi,sol,sagindex);
    if (solindex < sag) quicksort(gelendizi,solindex,sag);
}

Hiç yorum yok:

Yorum Gönder