I'm still working on implementing several sorting algorithms and wanted to implement a command-line menu where a user could chose the sorting algorithm he wants to use to sort the data. Every sorting algorithm has a "wrapper function" that takes the same arguments, the array containing the data and the size of that array. From there, every function does something specific to its algorithm.
My initial try to implement the menu was to first create an enumeration of the algorithms implemented and then create a switch() every time I want to use the specific algorithm:
Code:
typdef enum sort_e{
BUBBLE,
SELECTION,
INSERTION,
QUICK,
RADIX,
//...
} sortOption;
void startAlgorithm(int *array, size_t s, sortOption opt)
{
switch(opt)
{
case BUBBLE:
bubbleSort(array, s);
break;
case SELECTION:
selectionSort(array, s);
break;
// ...
}
}
This felt a little heavy and takes a lot of editing just to add a new algorithm.
I then was inspired by the way OO programming does it, so I did the following:
1. create a structure that keeps a function pointer:
Code:
typedef struct sort_t{
char name[BUFSIZ];
void (*pt2Func)(int*, int);
} sort;
2. Initialize an array of those structures, with the respective functions:
Code:
sort sortMethods[] = {
{"Bubble Sort", &bubbleSort},
{"Selection Sort", &selectionSort},
{"Insertion Sort", &insertionSort},
{"Merge Sort", &mergeSort},
{"Merge Sort (2 threads in parallel)", &mergeSortMulti},
{"Quick Sort (with fixed pivot)", &quickSort},
{"Quick Sort (with variable pivot)", &quickSortPivot},
{"Quick Sort (2 threads in parallel)", &quickSortMulti},
// ...
};
3. Finally, all I have to do is call the function pointer inside the structure:
Code:
(sortMethods[i]).pt2Func(array, arraySize);
Since I can't loop back on several years of C experience, I was wondering if that implementation style was well-known or even used at all? Maybe it has a specific name people refer it to (just guessing), since it seems so practical that it could be very common.
Is there maybe an even better of doing it or what solution do you prefer personally?
Thanks for the input.