[ZT] QSORT source code in VC, worth learning

xiaoxiao2021-03-06  52

.. /****Qsort.c - quicksort algorithm; qsort () library function for sorting arrays ** Copyright (c) Microsoft Corporation All rights reserved ** Purpose: * To implement the qsort () routine for sorting arrays *. *********************************************************** **************************** /

#include #include #include #include

/ * ALWAYS Compile this module for speed, not size * / # pragma optimize ("t", ON)

/ * prototypes for local routines * / static void __cdecl shortsort (char * lo, char * hi, size_t width, int (const void *, const void *); static void __cdecl swap (char * p, CHAR * Q, SIZE_T WIDTH;

/ * this parameter defines the cutoff BetWeen Using Quick Sort and INSERTION SORT for arrays; arrays with lengths shorter or equal to the best value use insertion sort * /

#define cutoff 8 / * Testing shows this is good value * /

/ **** qsort (base, num, wid, comp) - quicksort function for sorting arrays ** Purpose: * quicksort the array of elements * side effects: sorts in place * maximum array size is number of elements times size of elements , * but is limited by the virtual address space of the processor ** Entry: * char * base = pointer to base of array * size_t num = number of elements in the array * size_t width = width in bytes of each array element * int (* comp) () = Pointer to Function Returning Analog of strcmp for * strings, but support by user for committing the array elements. * IT Accepts 2 Pointers to elements and returns Neg iF 1 <2, 0 if * 1 = 2, POS IF 1> 2. ** EXIT: * RETURns void ** Exceptions: ****************************************** ******************************************************* / / * Sort the Array Between Lo and Hi (Inclusive) * /

#define stksiz (8 * sizeof (void *) - 2)

Void __cdecl qsort (void * base, size_t num, size_t width, int (__cdecl *) (const void *, const void *)) {/ * NOTE: The Number of Stack Entries Required is no more Than 1 log2 (NUM ), SO 30 is success, * hi; / * ends of sub-array currently sorting * / char * mid; / * points to middle of subarray * / char * loguy, * HIGUY; / * Traveling Pointers for Partition Step * / size_t size; / * size of the sub-array * / char * lostk [stksiz], * histk [stksiz]; int stacktr; / * stack for saving sub-array to be processed * /

IF (Num <2 || width == 0) return; / * Nothing to do * /

STKPTR = 0; / * Initialize stack * / lo = base; hi = (char *) Base width * (NUM-1); / * Initialize Limits * /

/ * This entry point is for pseudo-recursion calling: setting Lo and hi and jumping to here is like recursion, but start, locals aren't, so we preserve stuff on the stack * / recurse:

Size = (hi - lo) / width 1; / * Number of el's to sort * /

/ * BELOW a CERTAIN SIZE, IT IS FASTER TO USE A O (N ^ 2) Sorting Method * / IF (SIZE <= CUTOFF) {Shortsort (LO, Hi, Width, Comp);} else {/ * first We Pick a partitioning element. The efficiency of the algorithm demands that we find one that is approximately the median of the values, but also that we select one fast. We choose the median of the first, middle, and last elements, to avoid bad performance in the face of already sorted data, or data that is made up of multiple sorted runs appended together. Testing shows that a median-of-three algorithm provides better performance than simply picking the middle element for the latter case. * /

MID = LO (SIZE / 2) * width; / * Find Middle Element * /

/ * Sort the first, middle, limited elements INTO ORDER * / IF (COMP (LO, MID)> 0) {SWAP (LO, MID, WIDTH);} IF (COMP (LO, HI)> 0) {SWAP LO, Hi, Width;} IF (CoMP (MID, HI)> 0) {SWAP (MID, HI, Width);

/ * We now wish to partition the array into three pieces, one consisting of elements than it This is done below;. Comments indicate conditions established at every HiGuy = Hi;

/ * Note That HiGuy Decreases and Loguy Increases on EVERY ITERATION, SO LOOP MUST TERMINAT. * / For (;;) {/ * lo <= loguy a [mid] for hiGuy <= i = a [mid] * /

/ * The doubled loop is to Avoid Calling Comp (MID, MID), Since Some Existing Comparison Funcs Don't Work WHEN Passed The Same Value for Both Pointers. * /

IF (MID> LOGUY) {DO {LOGUY = Width;} While (Loguy

/ * LO hi or a [loguy]> a [mid] * /

Do {hiGuy - = width;} while (hiGuy> MID && Comp (HIGUY, MID)> 0);

/ * LO <= HIGUY a [MID] for HiGuy

HiGuy

/ * if loguy> hi or higuy == LO, THEN WE WOULD HAVE EXITED, SO A [LOGUY]> A [MID], A [HiGuy] <= a [MID], LOGUY <= Hi, HiGuy> LO * / Swap (Loguy, HiGuy, Width);

/ * If the part. ONLY NED to Check for Mid == HiGuy, Since Before The Swap, A [LOGUY]> A [MID] Implies Loguy! = MID. * /

IF (MID == HIGUY) MID = LOGUY;

/ * A [loguy] <= a [mid], a [hiGuy]> a [mid]; SO condition at top of loop is re-established * /}

/ * A [i] <= a [MID] for lo <= i a [mid] for HiGuy = a [mid] HIGUY

/ * Find Adjacent Elements Equal to the Partition Element. The Doubled Loop Is To Avoid Calling Comp (MID, MID), Since Some Existing Comparison Funcs Don't Work WHEN Passed The Same Value for Both Pointers. * /

HiGuy = width; if (Mid MID && Comp (HIGUY, MID) == 0);}} (MID> = HIGUY) {DO {hiGuy - = Width;} while (HIGUY> LO && Comp (HIGUY, MID) == 0);

/ * Ok, now we have the following: hiGuy a [mid] for loguy <= i = a [MID] * // * We've finished the partition, now Want to Sort the Subarrays [LO HiGuy] and [loguy, hi]. We do the smaller one first to minimize stack usage. We Only Sort Arrays of Length 2 or more. * /

IF (HiGuy - Lo> = Hi - LOGUY) {if (LO

IF (loguy

IF (lo

/ * WE HAVE SORTED THE ARRAY, EXCEPT for Any Pending Sorts on the stack. Check if there is all, and do them. * /

--stkptr; if (stkptr> = 0) {LO = lostk [stkptr]; hi = Histk [STKPTR]; goto recurse; / * Pop Subarray from stack * /} else return; / * all subarrays done * /}

/ **** Shortsort (Hi, Lo, Width, Comp) - Insertion Sort for Sorting Short Arrays ** Purpose: * Sorts the Sub-Array of Elements Between Lo and Hi (Inclusive) * Side Effects: Sorts in Place * Assumes That Lo 2. * * EXIT: * RETURNS VOID ** EXCEPTIONS: *************************************************** ******************************************************************************************** / Static void __cdecl Shortsort (Char * Lo, CHAR * HI, SIZE_T WIDTH, INT (__CDECL * COMP) (const void *, const void *) {char * p, * max;

/ * Note: in assertions below, I and j are alway inside original bound of array to sort. * /

While (hi> lo) {/ * a [i] <= a [j] for i <= j, j> hi * / max = Lo; for (p = lo width; p <= hi; p = Width {/ * a [i] <= a [max] for lo <= i

0) {Max = P;} / * a [i] <= a [MAX] for lo <= i <= p * /}

/ * A [i] <= a [max] for lo <= i <= hi * /

SWAP (MAX, HI, Width);

/ * A [i] <= a [hi] for i <= Hi, SO A [i] <= a [j] for i <= j, j> = hi * /

Hi - = width;

/ * A [i] <= a [j] for i <= j, j> hi, loop top condition establish * /} / * a [i] <= a [j] for i <= j, j> LO , Which Implies a [i] <= a [J] for i

Static void __cdecl swap (char * a, char * b, size_t width) {char TMP;

IF (a! = b) / * do the swap one character at a time to avoid potential alignment problems. * / while (width--) {tmp = * a; * a = * b; * b = TMP;}}

转载请注明原文地址:https://www.9cbs.com/read-82078.html

New Post(0)