The following code shows a C Program Using Function Pointer in Bubble Sort.

How to create a Function Pointer?

  1. Create a function. For example, void swap(int *arr, int y){….}
  2. In main()m create a function pointer. Also, assign the address of the function to the function pointer. For example, void (*sw)(int *, int)=&swap;
  3. Pass the function pointer as an argument in the function call. For example, BubbleSort(myarr, 10, *sw), where *sw is the function pointer.
  4. Similarly, specify the function pointer in function declaration. For example, void BubbleSort(int *arr, int Length, void (*sw)(int*, int));
  5. Finally, call the function by using the function pointer and provide actual parameters. For example, (*sw)(arr+j);
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void BubbleSort(int *arr, int Length, void (*sw)(int*, int));
void swap(int *arr, int y);

void BubbleSort(int *arr, int Length, void (*sw)(int*, int))
{
    int i, j, t, finished=1;
    for(i=0;i<9;i++)
    {
        for(j=0;j<9-i;j++)
        {
            if(*(arr+j) > *(arr+j+1)){
                (*sw)(arr, j);
                
                finished=0;
            }
        }
        if(finished)
            break;
    }
}
void swap(int *arr, int y)
{
    int t;
    t=*(arr+y);
    *(arr+y)=*(arr+y+1);
    *(arr+y+1)=t;
}
int main()
{
    int i, j, total, size, t, finished=1;
    int arr[10]={12, 90, 11, 89, 67, 55, 79, 18, 60, 49};
    int *myarr=arr;
    printf("Array before sorting...\n");
    for(i=0;i<10;i++)
        printf("%d ", *(myarr+i));
    void (*sw)(int *, int) = &swap;
    BubbleSort(myarr, 10, *sw);
    printf("\n\nArray after sorting...\n");
    for(i=0;i<10;i++)
        printf("%d ", *(myarr+i));

    return 0;
}

Output

The Output of the C Program Using Function Pointer in Bubble Sort
The Output of the C Program Using Function Pointer in Bubble Sort

Further Reading

50+ C Programming Interview Questions and Answers

C Program to Find Factorial of a Number