C program to sort integer array using qsort() with a function pointer

In this tutorial, we will learn about the qsort() function and how to sort integer array using qsort() with a function pointer using C program? By Nidhi Last updated : August 06, 2023

Problem statement

Here, we will create an array of integers with 5 items. Then we will arrange array elements in ascending order using qsort() function with a function pointer.

qsort() function

The qsort() is a standard library function in C programming language that is used to sort an array. As the name suggests, the qsort() function uses the quick sort algorithm to sort a given array. The syntax is,

void qsort (void* base, size_t num, size_t size, 
            int (*comparator)(const void*,const void*));

C program to sort integer array using qsort() with a function pointer

The source code to sort integer array using qsort() with function pointer is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to sort integer array
// using qsort with function pointer

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int compare(const void* numA, const void* numB)
{
    const int* num1 = (const int*)numA;
    const int* num2 = (const int*)numB;

    if (*num1 > *num2) {
        return 1;
    }
    else {
        if (*num1 == *num2)
            return 0;
        else
            return -1;
    }
}

int main()
{
    int arr[5] = { 50, 30, 20, 10, 40 };
    int i = 0;

    qsort(arr, 5, sizeof(int), compare);

    printf("Sorted Array: \n");
    for (i = 0; i < 5; i++)
        printf("%d ", arr[i]);
    printf("\n");

    return 0;
}

Output

Sorted Array: 
10 20 30 40 50

Explanation

In the above program, we created two functions compare() and main(). The compare() is used to compare two integer items.

In the main() function, we created an array of integers arr with 5 elements. Then we sorted the elements of the array using the qsort() function and printed the sorted array on the console screen.



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.