The understanding and use of the Qsort function in C and the sort function in C + +

Source: Internet
Author: User

one, qsort () function

Prototype: _crtimp void __cdecl qsort (void*, size_t, Size_t,int (*) (const void*, const void*));

Parameter explanation: 1, the first address of the array to be sorted, 2, the number of elements to be sorted in the array, 3, the size of the space occupied by each element, 4, a pointer to a function, to determine the order of the sort.

Description: The Qsort function is provided in the ANSI C standard, and its declaration in the Stdlib.h file is written according to the dichotomy, with the time Complexity O (N*LOGN).

Qsort requires a comparison function to determine the order of sorts (ascending, descending), and the comparison function makes the qsort more versatile and can be sorted by array, string, struct number. such as the int cmp (const void *a, const void *b) has two elements as parameters (the format of the parameter cannot be changed.) Returns an int value that, if the comparison function returns greater than 0,qsort, is considered a > b, and returns less than 0,qsort is considered a < B.

1. Several common CMP functions in Qsort

1.1. Sort an array of type int

int num[]; int cmp (constvoidconstvoid *b) {    return * ( int *) A-* (int *+sizeof(int), CMP);

1.2. Sort the array of char types

Char num[]; int cmp (constvoidconstvoid *b) {    return * ( Char *) A-* (char *+sizeof(char), CMP);

1.3. Sort the array of double types

double num[]; int cmp (constvoidconstvoid *b) {    return * ( Double *) a > * (double *sizeof(double), CMP) ;

1.4, the structure of the array of first-order sorting

structin{Doubledata; intOther ;} s[ -]//according to the value of data from small to large structure of the order, about the structure of the key data types can be many, refer to the above example to writeintcmpConst void*a,Const void*b) {    return(* (in *) a)->data > (* (in *) b)->data?1: -1;} Qsort (s), -,sizeof(inch), CMP);

1.5, the structure of the array of two-level sorting

structin{intx; inty;} s[ -];//Sort by x from small to large, when x is equal by y from largest to smallestintcmpConst void*a,Const void*b) {    structIn *c = (in *) A; structIn *d = (in *) b; if(C->x! = d->x)returnC->x-d->x; Else        returnD->y-c->y;} Qsort (s), -,sizeof(inch), CMP); 

1.6. Sort the strings

structin{intdata; Charstr[ -];} s[ -];//Sort by the dictionary order of the string str in the structintCMP (Const void*a,Const void*b) {    returnstrcmp ((* (*) a)->str, (* (in *) b)str);} Qsort (s), -,sizeof(in), CMP);

1.7. CMP for convex hull in computational geometry

 int cmp (const void *a,const void *b) // key CMP function,    To sort all points except 1 points, the rotation angle is  {  struct point *c= (Point *) A;     struct point *d= (Point *) b;  if(Calc (*c,*d,p[1]) < 0)
return 1; Else if(!calc (*c,*d,p[1]) && dis (c->x,c->y,p[1].x,p[1 ].y) < dis (d->x,d->y,p[1].x,p[1].y)) // If in a straight line, put the far forward return 1 ; Else        
return -1;}
2, expand the knowledge point

One, why use the Qsort function to specify the size of the sort element?

Ans: It's a brain problem, give me a brain-stump answer. Because the qsort needs to be sorted according to the size of the element.

Where is the const void* type accepted by the comparison function used?

Ans: Because of the versatility of the qsort, it is possible to sort arrays, structures, and so on.

Second, sort () function
Name of function Function Description
Sort Sort all elements of a given interval
Stable_sort Stable ordering of all elements in a given interval
Partial_sort Sort all elements of a given interval
Partial_sort_copy Copy and sort the given interval
Nth_element Find the element corresponding to a position in a given interval
is_sorted Determine if an interval has been sequenced.
Partition Put elements that meet a certain condition in front
Stable_partition Relatively stable so that elements that meet a certain condition are placed in front

To use the above function, you must add the header file algorithm.

1. Sort (begin,end)

Small example

#include <algorithm>int_tmain (intARGC, _tchar*argv[]) {     inta[ -]={2,4,1, at,5, the,0, +, -, $},i;  for(i=0;i< -; i++) cout<<a[i]<<Endl; Sort (A,a+ -);  for(i=0;i< -; i++) cout<<a[i]<<Endl; return 0;} 

The output is to sort the array a in ascending order, that is, the sort function is sorted by default in ascending order.

How to use the sort function in descending order, ok! Just like in qsort, we need to customize a comparison function CMP (the return value is type bool).

2. Overloaded sort function-sort with comparison function (BEGIN,END,CMP)

Methods for defining comparison functions

2.1. Common methods

The following comparison functions can be sorted in descending order:

BOOL cmp (int A,int  b) {    return a>b;      }

2.2. Use enum type enum to define ascending or descending sort.

// ASC Ascending, desc descending enum CMP{ASC,DESC};

2.3 Defines a comparison class that describes the order of the sort.

classcompare{Private: CMP comp;  Public: Compare (Cmp C): Comp (c) {}; BOOL operator() (intNUM1,intnum2) {            Switch(comp) { CaseASC:returnnum1<num2;  CaseDESC:returnNum1>num2; }          }};

Test it:

intMain () {inta[ -]={2,4,1, at,5, the,0, +, -, $},i;  for(i=0;i< -; i++) cout<<a[i]<<Endl; Sort (A,a+ -, compare (DESC));  for(i=0;i< -; i++) cout<<a[i]<<Endl; return 0;}

Know about it, because it is more troublesome, according to the actual situation.

2.4. Use the comparison object in the functional header file.

Functional provides a bunch of template-based comparison function objects. Equal_to<type>, not_equal_to<type>, greater<type>, greater_equal<type>, less<Type>, Less_equal<type>. For these objects of comparison, we can words too literally know what they mean.

For example:

Sort (begin,end,less<data-type> ();   Ascending sort (begin,end,greater<data-type> ();   Descending

Then the above example, using the comparison object

int_tmain (intARGC, _tchar*argv[]) {      inta[ -]={2,4,1, at,5, the,0, +, -, $},i;  for(i=0;i< -; i++) cout<<a[i]<<Endl; Sort (A,a+ -,greater<int>());  for(i=0;i< -; i++) cout<<a[i]<<Endl; return 0;}

three, qsort function and qsort function of PK.

1. CMP functions are different

The return value type is different, the CMP return value of the Qsort function is the Int,sort function, and the CMP return value is bool.

Parameters, the CMP of the sort function can be directly the reference type that participates in the comparison, and qsort is a strict null pointer type.

Unlike comparison expressions, the CMP in Qsort uses the "-" sign, and the CMP in sort uses ">".

2, the difference of performance

The sort function is a function of the standard template Library in C + +, which has been optimized on qsort () and can take different algorithms depending on the situation, so it is faster. The sort () executes faster than Qsort () under the same elements and the same comparison conditions. In addition, sort () is a generic function that can be used to compare any container, any element, any condition.

The understanding and use of the Qsort function in C and the sort function in C + +

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.