Free Web Hosting by Netfirms
Web Hosting by Netfirms | Free Domain Names by Netfirms

Home Page    

 

Quicksort Code

typedef int T;
typedef int TblIndex;

#define CompGT(a,b) (a > b)

T *Partition(T *Lb, T *Ub) {
    T V, Pivot, *I, *J, *P;
    unsigned int Offset;

   /*****************************
    *  partition Array[Lb..Ub]  *
    *****************************/

    /* select pivot and exchange with 1st element */
    Offset = (Ub - Lb)>>1;
    P = Lb + Offset;
    Pivot = *P;
    *P = *Lb;

    I = Lb + 1;
    J = Ub;
    while (1) {
        while (I < J && CompGT(Pivot, *I)) I++;
        while (J >= I && CompGT(*J, Pivot)) J--;
        if (I >= J) break;
        V = *I;
        *I = *J;
        *J = V;
        J--; I++;
    }

    /* pivot belongs in A[j] */
    *Lb = *J;
    *J = Pivot;

    return J;
}

void QuickSort(T *Lb, T *Ub) {
    T *M;

   /**************************
    *  Sort array A[Lb..Ub]  *
    **************************/

    while (Lb < Ub) {

        /* quickly sort short lists */
        if (Ub - Lb <= 12) {
            InsertSort(Lb, Ub);
            return;
        }

        /* partition into two segments */
        M = Partition (Lb, Ub);

        /* sort the smallest partition    */
        /* to minimize stack requirements */
        if (M - Lb <= Ub - M) {
            QuickSort(Lb, M - 1);
            Lb = M + 1;
        } else {
            QuickSort(M + 1, Ub);
            Ub = M - 1;
        }
    }
}

Back


user comments and suggestions are invited at KmailDrive@gmail.com