Generic quicksort in C
Recently I've learned how to use void pointers and function pointers in C and make functions generic as a part of MRND. So I've tried developing a generic quicksort function using it. I've implemented it in a header file so that it can be reused. Here's the gist for genericSort.h
The four arguments being sent into the genericQSort function are:
- void **arr: It's an array of pointers which holds the addresses of each element of the array that is to be sorted.
- int lo: The start index from where the array needs to be sorted.
- int hi: The end index till where the array needs to be sorted.
- int (*compare)(void *, void *): A function pointer to the user's implementation of how to compare the sent array. It returns -1, 1 or 0.
Here's a C program that makes use of the above function to sort an array of pairs. Here pair is a user-defined data-type which has two members x and y. The array is sorted based on the sum of x and y.
Here's a snap of execution of the program:
Comments
Post a Comment