C基礎--泛型函數

來源:互聯網
上載者:User

標籤:

#include <stdio.h>#include <time.h>#include <stdlib.h>void show_arry(int a[], int n){    int i;    for (i = 0; i < n; i++)        printf("%d\n", a[i]);    putchar(‘\n‘);}void init_arry(int a[], int n){    int i;    srand(time(NULL));    for (i = 0; i < n; i++)        a[i] = rand() % 100;}int cmp_int(void *a, void *b){    int x = *((int *)a);    int y = *((int *)b);    return x > y;}void swap_int(void *a, void *b){    int tmp;    tmp = *((int *)a);    *((int *)a) = *((int *)b);    *((int *)b) = tmp;}void bubble_sort(void *a, int n, int(*cmp)(void *, void *), void (*swap)(void *, void *)){    int i, j;    for (i = 0; i < n; i++)        for (j = 0; j < n-i-1; j++)            if (cmp((void *)((int *)a+j), (void *)((int *)a+j+1)) > 0)                swap((void *)((int *)a+j), (void*)((int*)a+j+1));}/*int main(void){    int a[10];    init_arry(a, 10);    show_arry(a, 10);    bubble_sort(a, 10, cmp_int, swap_int);    show_arry(a, 10);}*/int cmp_float(void *a, void * b){    return *((float *)a) > *((float *)b);}void swap_float(void *a, void *b){    float tmp;    tmp = *((float *)a);    *((float *)a) = *((float *)b);    *((float *)b) = tmp;}void show_float(float a[], int n){    int i;    for (i = 0; i < n; i++)        printf("%f\n", a[i]);    putchar(‘\n‘);}int main(void){    float a[5] = {1.3, 4.5, 2.3, 1.2, 3.7};    bubble_sort(a, 5, cmp_float, swap_float);    show_float(a, 5);}

 

C基礎--泛型函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.