How to sort by using qsort in C-function data

Source: Internet
Author: User

# Include <stdio. h>

# Include <stdlib. h>

# Include <time. h>

 

Int compare (const void * a, const void * B) // This function is a comparison function required by qsort.
{
Int c = * (int *);
Int d = * (int *) B;
If (C <D) {return-1;} // If-1 is returned, a <B
Else if (C = d) {return 0;} // return 0 indicates a = B
Else return 1; // return 1 indicates A> B
}

/* The following parts can be used for comparing strings:

Int compare (const void * a, const void * B)

{

Return (strcmp (char *) A, (char *) B ));

}

*/

 

Void main ()

{

Int A [100], I;

Srand (unsigned) Time (null ));

For (I = 0; I <100; I ++)
A [I] = rand (); // The number of data products generates 100 words

For (unsigned I = 0; I <100; I ++)
{
Printf ("% d/T", a [I]); // print the content Before sorting
}

Printf ("/N ");

/*Qsort function description-># Include <stdlib. h>

VoidQsort(Void * base, size_t N, size_t size, INT (* CMP) (const void *, const void *)Function, The cursor column is the cursor data base, n is the cursor column size, size is the size of each element, and the last cursor number is pointingFunctionWhich is larger than the limit element.Function (that is, the above compare () function).

*/

Qsort ((Void *), 100,Sizeof (A [0]),Compare);

For (unsigned I = 0; I <100; I ++)

{

Printf ("% d/T", a [I]); // print the content after sorting

}

System ("pause ");

}

 

 

Appendix qsort. C (MS/CRT /)

 

/***
* 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 <cruntime. h>
# Include <stdlib. h>
# Include <search. h>
# Include <internal. h>

/* 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 (_ cdecl * comp) (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
Below value use insertion sort */

# Define cutoff 8/* testing shows that 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
* Strings, but supplied by user for comparing 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 (random SIVE )*/

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

Void _ cdecl qsort (
Void * base,
Size_t num,
Size_t width,
INT (_ cdecl * comp) (const void *, const void *)
)
{
/* Note: The number of stack entries required is no more
1 + log2 (Num), so 30 is sufficient for any array */
Char * Lo, * 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 stkptr;/* 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 stkptr is
Preserved, 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
Algorithm demands that we find one that is approximately the median
Of the values, but also that we select one fast. We choose
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
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, last 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 <= partition element, one of elements equal to
Partition element, and one of elements> than it. This is done
Below; comments indicate conditions established at every step .*/

Loguy = lo;
Higuy = Hi;

/* Note that higuy decreases and loguy increases on every iteration,
So loop must terminate .*/
For (;;){
/* Lo <= loguy A [I] <= A [Mid] For lo <= I <= loguy,
A [I]> A [Mid] For higuy <= I A [HI]> = 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 <Mid & Comp (loguy, mid) <= 0 );
}
If (mid <= loguy ){
Do {
Loguy + = width;
} While (loguy <= Hi & Comp (loguy, mid) <= 0 );
}

/* Lo <loguy <= Hi + 1, a [I] <= A [Mid] For lo <= I <loguy,
Either loguy> Hi or a [loguy]> A [Mid] */

Do {
Higuy-= width;
} While (higuy> mid & Comp (higuy, mid)> 0 );

/* Lo <= higuy Either higuy = lo or a [higuy] <= A [Mid] */

If (higuy <loguy)
Break;

/* If loguy> Hi or higuy = Lo, then we wowould have exited, so
A [loguy]> A [Mid], a [higuy] <= A [Mid],
Loguy <= Hi, higuy> lo */

Swap (loguy, higuy, width );

/* If the partition element was moved, follow it. Only Need
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 <loguy,
A [I]> A [Mid] For higuy <I A [HI]> = A [Mid]
Higuy <loguy
Implying:
Higuy = loguy-1
Or higuy = Hi-1, loguy = Hi + 1, a [HI] = A [Mid] */

/* Find adjacent elements equal to the partition element.
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 Do {
Higuy-= width;
} While (higuy> mid & Comp (higuy, mid) = 0 );
}
If (mid> = higuy ){
Do {
Higuy-= width;
} While (higuy> lo & Comp (higuy, mid) = 0 );
}

/* OK, now we have the following:
Higuy <loguy
Lo <= higuy <= Hi
A [I] <= A [Mid] For lo <= I <= higuy
A [I] = A [Mid] For higuy <I <loguy
A [I]> A [Mid] For loguy <= I A [HI]> = A [Mid] */

/* We 've finished the partition, now we 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 Lostk [stkptr] = lo;
Histk [stkptr] = higuy;
++ Stkptr;
}/* Save Big recursion for later */

If (loguy Lo = loguy;
Goto recurse;/* do small recursion */
}
}
Else {
If (loguy Lostk [stkptr] = loguy;
Histk [stkptr] = Hi;
+ Stkptr;/* Save Big recursion for later */
}

If (Lo Hi = higuy;
Goto recurse;/* do small recursion */
}
}
}

/* We have sorted the array, should t for any pending sorts on the stack.
Check if there are any, 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 (random SIVE)
* Side effects: sorts in place
* Assumes that lo *
* Entry:
* Char * Lo = pointer to low element to sort
* Char * Hi = pointer to high element to sort
* Size_t width = width in bytes of each array element
* Int (* comp) () = pointer to function returning analog of strcmp
* Strings, but supplied by user for comparing 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:
*
**************************************** ***************************************/

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
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 <p */
If (COMP (p, max)> 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 established */
}
/* A [I] <= A [J] For I <= J, j> Lo, which implies a [I] <= A [J] For I <J,
So array is sorted */
}

/***
* Swap (a, B, width)-swap two elements
*
* Purpose:
* Swaps the two array elements of size width
*
* Entry:
* Char * a, * B = pointer to two elements to swap
* Size_t width = width in bytes of each array element
*
* Exit:
* Returns void
*
* Exceptions:
*
**************************************** ***************************************/

Static void _ cdecl swap (
Char *,
Char * B,
Size_t width
)
{
Char TMP;

If (! = B)
/* Do the swap one character at a time to avoid potential alignment
Problems .*/
While (width --){
TMP = *;
* A ++ = * B;
* B ++ = TMP;
}
}
 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.