#Passing functions as arguments to other functions to sort an array

5 messages · Page 1 of 1 (latest)

graceful orioleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

lunar moon
#

!format

graceful orioleBOT
#
bool (*comparisonFcn)(int, int);

COPY

    So,
    we’ll allow the caller to pass our sort routine a pointer to their desired
        comparison function as the third parameter,
    and then we’ll use the caller’s function to do the comparison.Here’s a full
            example of a selection sort that uses a function pointer parameter
                to do a user -
        defined comparison,
    along with an example of how to call it:

#include <utility>  #include <iostream>  void selectionSort(int* array, int size, bool (*comparisonFcn)(int, int)) {  for (int startIndex{ 0 }; startIndex < (size - 1); ++startIndex) { int bestIndex{ startIndex };  for (int currentIndex{ startIndex + 1 }; currentIndex < size; ++currentIndex) {  if (comparisonFcn(array[bestIndex], array[currentIndex])) { bestIndex = currentIndex; } }  std::swap(array[startIndex], array[bestIndex]); } } bool ascending(int x, int y) { return x > y;  }  bool descending(int x, int y) { return x < y;  }  void printArray(int* array, int size) { for (int index{ 0 }; index < size; ++index) { std::cout << array[index] << ' '; } std::cout << '\n'; } int main() { int array[9]{ 3, 7, 9, 5, 6, 1, 8, 2, 4 };  selectionSort(array, 9, descending); printArray(array, 9); selectionSort(array, 9, ascending); printArray(array, 9);
Oppenheimer
#

@lunar moon

Please Do Not Delete Posts!

Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.

lunar moon
#

!solved