Application of callback function __ function

Source: Internet
Author: User
1 Back-tune function 1.1 Problem leads

When we want to implement the sort, ascending and descending, are written dead in the program, if you want to change only
The original code, then if the program is given in the form of a library. And so what?

#include <stdio.h>
void selectsort (int *p, int n)
{for
    (int i=0; i<n-1 i + +)
    {for
        (int j=i +1; j<n; J + +)
        {
            if (P[i] < p[j])
            {
                P[i] = p[i]^p[j];
                P[J] = p[i]^p[j];
                P[i] = p[i]^p[j]; 
}}} int main (void)
{
    int arr[10] = {6,5,4,3,2,1,7,8,9,0};
    Selectsort (arr,10);
    for (int i=0; i<10; i++)
    {
        printf ("%d\n", Arr[i]); 
    return 0;
}
1.2 callback (function as parameter)

To solve the problem of not modifying the original code or the library file, we provide a callback function for the sort function. ·

 #include <stdio.h> int callbackcompare (int a,int b) {return a<b?1:0;} void selects
        ORT (int *p, int n,int (*PF) (Int,int)) {for (int i=0; i<n-1; i + +) {for (int j=i+1; j<n; j + +)
                {if (PF (P[i],p[j])) {P[i] = p[i]^p[j];
                P[J] = P[i]^p[j];
            P[i] = P[i]^p[j];
    int main (void) {int arr[10] = {6,5,4,3,2,1,7,8,9,0};
    Selectsort (Arr,10,callbackcompare);
    for (int i=0; i<10; i++) {printf ("%d\n", Arr[i]);
return 0; }

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.