ADVERTISEMENT
ADVERTISEMENT

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

Here, we are going to learn how to sort integer array using qsort() with a function pointer using C program?
Submitted by Nidhi, on August 15, 2021

Problem Solution:

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*));

Program:

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.

ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.