龙空技术网

C|排序算法使用函数指针参数来自定义排序方式

小智雅汇 151

前言:

目前同学们对“c语言reverse函数使用”大致比较看重,朋友们都需要知道一些“c语言reverse函数使用”的相关知识。那么小编同时在网上汇集了一些对于“c语言reverse函数使用””的相关知识,希望姐妹们能喜欢,姐妹们快快来学习一下吧!

如果定义一个排序函数,试图通过一个参数来选择排序方式,怎样实现?通过定义函数来定义排序方式,在排序函数参数中使用一个函数指针,调用时用实际的函数名来传参给函数指针。

#include <stdio.h>#include <stdlib.h>#include <errno.h>#include <string.h>void die(const char *message){ if (errno) { perror(message); } else { printf("ERROR: %s\n", message); } exit(1);}// a typedef creates a fake type, in this// case for a function pointertypedef int (*compare_cb) (int a, int b);	//实参→形参时联系两个函数 /** * A classic bubble sort function that uses the  * compare_cb to do the sorting.  */int *bubble_sort(int *numbers, int count, compare_cb cmp){ int temp = 0; int i = 0; int j = 0; int *target = malloc(count * sizeof(int)); if (!target) die("Memory error."); memcpy(target, numbers, count * sizeof(int)); for (i = 0; i < count; i++) { for (j = 0; j < count - 1; j++) { if (cmp(target[j], target[j + 1]) > 0) { temp = target[j + 1]; target[j + 1] = target[j]; target[j] = temp; } } } return target;}int sorted_order(int a, int b)//compare_cb cmp1 { return a - b;}int reverse_order(int a, int b)//compare_cb cmp2 { return b - a;}int strange_order(int a, int b)//compare_cb cmp3{ if (a == 0 || b == 0) { return 0; } else { return a % b; }}/**  * Used to test that we are sorting things correctly * by doing the sort and printing it out. */void test_sorting(int *numbers, int count, compare_cb cmp){ int i = 0; int *sorted = bubble_sort(numbers, count, cmp); if (!sorted) die("Failed to sort as requested."); for (i = 0; i < count; i++) { printf("%d ", sorted[i]); } printf("\n"); free(sorted);}void destroy(compare_cb cmp){ int i = 0; unsigned char *data = (unsigned char *)cmp; for(i = 0; i < 1; i++) { data[i] = i; } printf("\n");}void dump(compare_cb cmp)//函数指针指向的内容用字符串输出(或少或多) { int i = 0; unsigned char *data = (unsigned char *)cmp; for(i = 0; i < 25; i++) { printf("%02x:", data[i]); } printf("\n");}int main(int argc, char *argv[]){ if (argc < 2) die("USAGE: ex18 4 3 1 5 6"); int count = argc - 1; int i = 0; char **inputs = argv + 1; int *numbers = malloc(count * sizeof(int)); if (!numbers) die("Memory error."); for (i = 0; i < count; i++) { numbers[i] = atoi(inputs[i]); } test_sorting(numbers, count, sorted_order); test_sorting(numbers, count, reverse_order); test_sorting(numbers, count, strange_order); free(numbers); printf("SORTED:"); dump(sorted_order); destroy(sorted_order); printf("SORTED:"); dump(sorted_order); return 0;}/*F:\2C\hardwayC\ex18>F:\2C\hardwayC\ex18\ex18.exe 1 3 5 3 9 9 2 8 5 31 2 3 3 3 5 5 8 9 99 9 8 5 5 3 3 3 2 19 5 9 3 3 8 2 5 3 1SORTED:55:89:e5:8b:45:08:2b:45:0c:5d:c3:55:89:e5:8b:45:0c:2b:45:08:5d:c3:55:89:e5:F:\2C\hardwayC\ex18>pause*/

-End-

标签: #c语言reverse函数使用