[C Language] use the callback function to Implement Bubble Sorting

Source: Internet
Author: User

[C Language] use the callback function to Implement Bubble Sorting
Function: You can sort the integer or string as follows:

#include <stdio.h>#include <string.h>int int_cmp(const void *p1, const void *p2){    if (*(int *)p1 > *(int *)p2)    {        return 1;    }    else if (*(int *)p1 == *(int *)p2)    {        return 0;    }    else    {        return -1;    }}void swap(void *p1, void *p2, int size){    int i = 0;    for (i = 0; i < size; i++)    {        char tmp = *((char *)p1 + i);        *((char *)p1 + i) = *((char *)p2 + i);        *((char *)p2 + i) = tmp;    }}void bubble(void *base, int count, int size, int(*cmp)(const void *, const void *)){    int i = 0;    int j = 0;    for (i = 0; i < count - 1; i++)    {        for (j = 0; j < count - i - 1; j++)        {            if (cmp((char *)base +size*j,(char *)base+size*(j+1))>0)            {                swap((char *)base + size*j, (char *)base + size*(j + 1), size);            }        }    }}int str_cmp(const void *p1, const void *p2){    return strcmp((char *)(*(int *)p1), (char *)(*(int *)p2));}int main(){    //int arr[] = { 1, 3, 5, 7, 9, 2, 4, 6, 8, 0 };    char *arr[] = { "dddd", "bbbb", "cccc", "aaaa" };    int i = 0;    bubble(arr, sizeof(arr) / sizeof(arr[0]), sizeof(char *), str_cmp);    for (i = 0; i < 4; i++)    {        printf("%s\n", arr[i]);    }    printf("\n");    return 0;}

 


Related Article

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.