0

I have an exercise to implement two function ascendingSort, descendingSort and function mySort.

#include<iostream>
#include <math.h>
using namespace std;

void ascendingSort(int a[], int n) {
     //TODO
}

void descendingSort(int a[], int n) {
    //TODO
}

void mySort(int a[], int n, void (*sort)(int[], int)) {
    /*
     * STUDENT ANSWER
     * TODO: sort array based on sort algorithm of function sort. 
     */
}

int main() {
    int n = 5;
    int a[5] = { 1, 2, 3, 4, 5 };
    void (*sortAlgorithm)(int[], int) = descendingSort;
    
    mySort(a, n, sortAlgorithm);
    for (int i = 0; i < n; ++i) {
    printf("%d ", a[i]);
    }
    return 0;
}

I can implement two sort function. But I don't know how to write function mySort Can you give me any ideas? Thank you!

hidaimrd
  • 1
  • 1
  • 2
    What are the requirements for `mySort()`? Without specifying that we can't help you here. – πάντα ῥεῖ Oct 03 '20 at 15:45
  • 1
    Provided that you have implemented descendingSort and ascendingSort, I think mySort should just call the "sort" function pointer with appropriate arguments. – Sven Nilsson Oct 03 '20 at 15:50
  • @πάνταῥεῖ function `mySort()` is to decide whether use ascendingSort or descendingSort. You can see in `main()` – hidaimrd Oct 03 '20 at 15:54
  • @SvenNilsson, furthermore, the OP does not even need separate function for ascending and descending sort – kesarling He-Him Oct 03 '20 at 15:55
  • @SvenNilsson Yes, but I don't know how to call function pointer in this case :(((( – hidaimrd Oct 03 '20 at 15:56
  • You don't need to, C++ allows it to be called pretty much like any normal function – Sven Nilsson Oct 03 '20 at 15:58
  • @hidaimrd Just use `sort(a,n);` to call from the function pointer inside `mySort()`. – πάντα ῥεῖ Oct 03 '20 at 15:59
  • @πάνταῥεῖ but how can I pass value to `void (*sort) (int [], int)` (to sort ascending or descending) – hidaimrd Oct 03 '20 at 16:09
  • @hidaimrd You already do this: `void (*sortAlgorithm)(int[], int) = descendingSort; mySort(a, n, sortAlgorithm);` In that case you've chosen to sort descending. – πάντα ῥεῖ Oct 03 '20 at 16:10
  • @hidaimrd: *"You can see in `main()`"* -- your code does not work as intended, yet you expect us to infer the intent from how the code works??? A much better idea is to use sentences (or perhaps even paragraphs) in your question to describe the intended functionality. The code should be an illustration of your question, not the primary source of information. – JaMiT Oct 03 '20 at 16:12
  • I solved the problem, thank you very much – hidaimrd Oct 03 '20 at 16:15

0 Answers0