Function Pointers and qsort in C

 Function Pointers and qsort in C


Function pointers can be used in conjunction with the qsort function from the standard library to sort arrays. qsort allows you to sort elements based on a specified comparison function.


#include <stdio.h>

#include <stdlib.h>


int compare(const void* a, const void* b) {

    int num1 = *(int*)a;

    int num2 = *(int*)b;


    if (num1 < num2) {

        return -1;

    } else if (num1 > num2) {

        return 1;

    }


    return 0;

}


int main() {

    int nums[] = {5, 2, 8, 1, 4};

    int numCount = sizeof(nums) / sizeof(nums[0]);


    qsort(nums, numCount, sizeof(int), compare);


    printf("Sorted array: ");

    for (int i = 0; i < numCount; i++) {

        printf("%d ", nums[i]);

    }

    printf("\n");


    return 0;

}

In this example, the compare function defines the comparison logic for sorting integers in ascending order. The qsort function is then used to sort the nums array using the compare function as the sorting criterion.


No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...