Generic programming and C ++ Standard Template Library: Talking About sort () sorting function and sort

Source: Internet
Author: User

Generic programming and C ++ Standard Template Library: Talking About sort () sorting function and sort

Previously, when sorting With sort, we only know that the sort function has the following two overload methods.

At that time, I was not very familiar with these parameters. I only knew some simple usage.

1). For example, the following code can arrange array a in ascending order.

Int a [5] = {1, 6, 9, 4, 5 };

Sort (a, a + 5 );

2). The following code can be used to sort data in a set sorting method.

Bool cmp (int a, int B)

{

Return a> B;

}

Int main ()

{

Int a [5] = {4, 3, 2, 7, 8 };

Sort (a, a + 5, cmp );

Return 0;

}

Of course, the sort () function must contain the algorithm header file # include <algorithm>.

Next, let's briefly analyze the implementation of the sort () function:

Let's first take a look at the sort () source code. Here we take a screenshot, 1:


Through this, we can clearly see that the sort () sorting in the template library is still relatively complicated, and there are nested fast sorting, heap sorting, and inserting several different sorting methods. At the same time, different sorting schemes are called based on different data to achieve relatively fast sorting.


Of course, here is a simple analysis of the sort () source code. To be clear, we divide the steps into several steps and analyze them step by step.


Step 1: There is no need to arrange the quick heap of the template library here. For the sake of simplicity, directly bubble up:

/// ///Date: august 1, 2014 14:14:35 // IDE: VS2010 // Author: dujun Qing // 1). simple Bubble Sorting # include <iostream> using namespace std; void maopao (int a [], int len) {int I, j; int t = 0; for (I = 1; I <len; ++ I) {for (j = 0; j <len-1; ++ j) {if (a [j]> a [j + 1]) {t = a [j]; a [j] = a [j + 1]; a [j + 1] = t ;}}} int main (void) {int I, a [] = }; int len = sizeof (a)/sizeof (a [0]); maopao (a, len); for (I = 0; I <len; ++ I) {cout <a [I] <";}cout <endl; return 0 ;}

Step 2: Use Bubble sorting to simulate the two overload methods of the sort () function. The second overload method obviously needs to introduce the function pointer.

// 2 ). introduce function pointer # include <iostream> using namespace std; // Compare function bool Max (int a, int B) {return a <B;} // bool (* cmp) (int, int): a function pointer // indicates that the function type to be pointed to is: The returned value is bool, and two int parameters void maopao (int a [], int len, bool (* cmp) (int, int) {int I, j; int t = 0; for (I = 1; I <len; ++ I) {for (j = 0; j <len-1; ++ j) {if (cmp (a [j], a [j + 1]) // note that the function is called directly here -- passing the parameter to obtain the returned value {t = a [j]; a [j] = a [j + 1]; a [j + 1] = t ;}}} int main (void) {int I, a [] = }; int len = sizeof (a)/sizeof (a [0]); maopao (a, len, Max); // 3rd parameters (function name ): for the comparison method for (I = 0; I <len; ++ I) {cout <a [I] <";}cout <endl; return 0 ;}
Step 3: templated the above Code to support sorting of multiple types of data.

// 3 ). introduces the template concept and supports multiple types # include <iostream> using namespace std; // comparison function template <class T> bool Max (T a, T B) {return a> B;} // function template <class T, class Func> void maopao (T a [], int len, Func cmp) {int I, j; T t; for (I = 1; I <len; ++ I) {for (j = 0; j <len-1; ++ j) {if (cmp (a [j], a [j + 1]) // call the function directly here -- pass the parameter to obtain the return value {t = a [j]; a [j] = a [j + 1]; a [j + 1] = t ;}}// overload function template, by default, the template <class T> void maopao (T a [], int len) {int I, j; T t; for (I = 1; I <len; ++ I) {for (j = 0; j <len-1; ++ j) {if (a [j]> a [j + 1]) {t = a [j]; a [j] = a [j + 1]; a [j + 1] = t ;}}} int main (void) {int I, a [] = {,}; int len = sizeof (a)/sizeof (a [0]); // maopao (, len); // by default, maopao (a, len, Max <int>) is sorted in ascending order; // 3rd parameters (function name ): for the comparison method for (I = 0; I <len; ++ I) {cout <a [I] <";}cout <endl; return 0 ;}
Step 4: the above steps have basically implemented the sort () function of the template library, but the input parameters seem to be incorrect. For this reason, we will make the following adjustments and changes, at the same time, replace the Bubble sorting with the fast sorting.

// 3 ). modify the sorting function to make it conform to the sort (a, a + 10), sort (a, a + 10, cmp) mode, at the same time, the sort () function of the system can be changed to a fast sort // There are two reload Methods // 1. sort (iterator 1, iterator 2); // 2. sort (iterator 1, iterator 2, predicate method); // note: in fact, the sorting method selected by the sort () function is complicated, including, heap, insert sorting ). // and sort () will select different sorting schemes based on different data. Here we only take the quick sorting as an example. # include <iostream> using namespace std; // comparison function template <class T> bool Max (T a, T B) {return a> B ;} // function template (using quick sorting) template <class T, class Func> void Qsort (T * begin, T * end, Func cmp) {T t = * begin; T * pL = begin, * pR = (end-1); if (pL> = pR) {return;} else {while (pL <pR) {while (cmp (t, * pR) & pL <pR) {-- pR;} * pL = * pR; while (cmp (* pL, t) & pL <pR) {++ pL;} * pR = * pL;} * pL = t;} Qsort (pL + 1, end, cmp); Qsort (begin, pR-1, cmp);} // reload function template, default sort Scheme (small to large) template <class T> void Qsort (T * begin, T * end) {T t = * begin; T * pL = begin, * pR = (end-1); if (pL> = pR) {return ;} else {while (pL <pR) {while (t <* pR & pL <pR) {-- pR;} * pL = * pR; while (* pL <= t & pL <pR) {++ pL;} * pR = * pL;} * pL = t;} Qsort (pL + 1, end); Qsort (begin, pR-1);} int main (void) {int I, a [] = {17,82, 37,89, 67,15 }; int len = sizeof (a)/sizeof (a [0]); // Qsort (a, a + len); Qsort (a, a + len, max <int>); for (I = 0; I <len; ++ I) {cout <a [I] <"" ;}cout <endl; return 0 ;}

Address: http://blog.csdn.net/qingdujun/article/details/38342951



Compile a sort function to sort arrays of any type.

For the sake of convenience, some standard library functions are used in the program, so two header files need to be included. The sort () function uses the selection Sorting Algorithm to sort the array, the parameters to be passed in during the call are consistent with the standard library function qsort ().

# Include <stdlib. h>
# Include <string. h>

Void sort (void * base, unsigned int n, unsigned int width, int (* comp) (void * a, void * B ))
{
Char * p = (char *) base;
Char * te = (char *) malloc (width );
Char * ptr;
Char * pn = p + width;
Const char * cp = p + (n-1) * width;

For (; p <cp; p + = width ){
Ptr = p;
For (pn = p + width; pn <= cp; pn + = width)
If (* comp) (ptr, pn)> 0) ptr = pn;
If (ptr! = P ){
Memcpy (te, p, width );
Memmove (p, ptr, width );
Memmove (ptr, te, width );
}
}

Free (te );
}
 
C ++ STL generic programming sort algorithm problems

You mean that the parameter included in the sort generic algorithm has a predicate. The predicate is equivalent to one parameter in sort, but the predicate itself is a function. Here you are a function that returns the bool type. This function has two parameters, the const references to the form parameters a and B respectively, and then compares whether a and B are equal. If a is not equal to B, return a> B returns the value of expression a> B, if a is greater than B, the value is true; otherwise, the value is false. else return a> B, where a = B is returned. Otherwise, false is returned.
The following is called in the sort algorithm, for example, a vector container that defines an int.
Vector <int> ivec;
Sort (ivec. begin (), ivec. end (), Comp );
Remember that parameters cannot be followed by Comp. Simply write the function name and sort the result according to the return result of the function to true, that is, sort the result from large to small.

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.