#include <stdio.h> #define N 10//defines the number of array elements int ascending (int a,int b);//function declaration in ascending order int descending (int a,int b);// Functions declared in descending order void swap (int*,int*);//function declaration of Data Interchange void Bubblesort (int a[],int n,int (*compare));//Declaration sort function, call void Display (int a[],int n) through a function pointer as a function;//function declaration of the output Array element void Main () {int a[n]={12,34,21,46,89,54,26,8,6,17};int flag; while (1) {printf ("Input 1: Sort from small to large. \ n Input 2: From large to small sort \ n Enter 3: Exit!\ n "); scanf ("%d ", &flag); switch (flag) {case 1:printf (" The data before sorting is: "); Display (A,n); Bubblesort (a,n,ascending);//From small to large sort. Pass the function as a parameter to printf ("data from small to large:");D Isplay (a,n), Break;case 2:printf ("The data before sorting is:"); Display (A,n); Bubblesort (a,n,descending);//Sort from large to small. Pass the function as a reference to printf ("data from large to small:");D Isplay (a,n), break;case 3:return;break;default:printf ("Input data is illegal, please enter again.") \ n "); break;}} Bubble sort, pass function as a parameter, infer whether from small to large or from large to small sort void bubblesort (int a[],int n,int (*compare) (int,int)) {int i,j;for (i=0;i<n;i++) { for (j=0;j<n-1;j++) if ((*compare) (a[j],a[j+1)) swap (&a[j],&a[j+1]);}} Swaps the elements of the array void swap (int *a,int *b) {int t;t=*a;*a=*b;*b=t;} Infer the size of adjacent data, assuming that the former is large, ascending order need to exchange int ascending (int a,int b) {if (a>b) return 1;elsereturn 0;} Infer the size of the adjacent data, assuming that the former large, descending order need to exchange int descending (int a,int b) {if (a<b) return 1;elsereturn 0;} void Display (int a[],int n)//output data element {int i;for (i=0;i<n;i++) printf ("%5d", A[i]);p rintf ("\ n");}
Program execution Results
function pointers as function parameters for ascending and descending sorting of bubbling sort