Hello, I am writing a program that checks if a sort routine (in this case, insertion sort) being used is stable. For this particular program, I have to use function pointer to pass the function of the sort routine.
1. How do you pass insertion_sort function as a parameter? I've tried to do this but length and arr are not initialized so it doesn't know that I am taking insertion_sort and putting it into stable_sort
2. Why am I getting error messages in line 38 and 40?
#include <iostream>
usingnamespace std;
bool stable_sort(void ) // how to pass insertion_sort function as a parameter?
{
for (int i = 0; i < length; i++)
{
if (arr[i] < arr[i+1])
returntrue;
else
cout << "The sort is not stable! " << endl;
returnfalse;
}
}
void insertion_sort(int arr[], int length)
{
int i, j ,tmp;
for (i = 1; i < length; i++)
{
j = i;
while (j > 0 && arr[j - 1] > arr[j])
{
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}//end of while loop
}//end of for loop
}//end of insertion_sort.
int main()
{
int c;
int length = 5;
int arr[5] = {5,4,3,2,1};
void (*pfnc)(int arr[], int);
pfnc = & insertion_sort;
c = (*pfnc)(arr, length);
stable_sort(c);
return 0;
}
bool stable_sort(int arr[], int length) // how to pass insertion_sort function as a parameter?
{
for (int i = 0; i < length; i++)
{
if (arr[i] < arr[i+1])
returntrue;
else
cout << "The sort is not stable! " << endl;
returnfalse;
}
}
int main()
{
int c;
int length = 5;
int arr[5] = {5,4,3,2,1};
void (*pfnc)(int arr[], int);
pfnc = insertion_sort;
c = pfnc(arr, length);
stable_sort(arr, length);
return 0;
}
Thank you for helping, but I have few questions about your code.
1. If I implemented your code, what is the point of having code line 18 - 20?
2. I specifically mentioned that you are not supposed to pass array and int in bool stable_sort. Instead, you are supposed to pass a function pointer.
This function pointer is going to be the function of the sort (in this case, it is insertion sort). How can I pass the insertion_sort to the bool stable_sort?
Just like a normal function pointer. Normally I would say to use std::function, but considering this appears to be a homework assignment or the like I'll just show you the way its normally done:
I'm not certain if I got this right though. Function pointers are just messy, its normally better to use std::function. This should give you an idea, though.
I'm not going to go into the logic errors in your code - I don't have time at the moment, I may reply back if I get the time. Hope you work it out, though!