Home > OS >  How to replace function calls with array of #define in C
How to replace function calls with array of #define in C

Time:12-20

I am trying to compare different sorting algorithms in one loop. I have #defined function calls in a string array, but it doesn't call the functions as intended. What could be the problem?

function calls array:

const char sorts[][30] = {"bubbleSort(arr, size)", "quickSort(arr, 0, size-1)", "insertionSort(arr, size)",
                      "selectionSort(arr, size)", "mergeSort(arr, 0, size)"};

Calling functions using array:

for(int i = 0; i < NUMBER_OF_SORTS;   i) {
    sorts[i];
}

I am sure there is a working way, thanks for help in advance.

CodePudding user response:

First, declare a type to represent a sorting function (supposing your sorting functions accept arrays of integers):

typedef void (SORTING_FUNCTION)(int*, size_t);

Then, define an array of pointers to your sorting functions (here, hungarian notation for the C language would merely propose snake case, bubble_sort, while for C it would be camel case bubbleSort, as you did):

SORTING_FUNCTION *sort[] = 
{ 
 bubbleSort,
 quick_sort_wrapper,
 insertionSort,
 selectionSort,
 mergeSort
};

and call it so:

sort[i](array, size);

taking i from 0 up to 4 in this case.

EDIT: If some sorting function takes additional arguments, for example quickSort, then instead of calling quickSort directly, you define a wrapper function quick_sort_wrapper which will have a SORTING_FUNCTION signature and this function will call quickSort, passing it an additional argument, apart from array and size.

CodePudding user response:

This is probably the best approach for a beginner, leaving yourself the best opportunity to get help from the compiler.

switch (i) {
  case 0:
    bubbleSort(arr, size);
    break;
  case 1:
    quickSort(arr, 0, size-1);
    break;
  case 2:
    insertionSort(arr, size);
    break;
  case 3:
    selectionSort(arr, size);
    break;
  case 4:
    mergeSort(arr, 0, size);
    break;
}
  • Related