01/10/2018, 16:08

Cho mình hỏi về đoạn này trong con trỏ hàm

#include <iostream>
using namespace std;
void printArray(int arr[],int n)
{
    for (int i=0;i<n;i++)
        cout <<arr[i]<<" ";
}
bool ascending(int left, int right)
{
    return left > right;
}
bool descending(int left, int right)
{
    return left < right;
}
void selectionSort(int *arr, int length, bool (*comparisonFunc)(int, int))
{
    for (int i_start = 0; i_start < length; i_start++)
    {
	    int minIndex = i_start;
	    for (int i_current = i_start + 1; i_current < length; i_current++)
	    {
		    if (comparisonFunc(arr[minIndex], arr[i_current])) // use function pointer as ascending or descending function
		    {
			    minIndex = i_current;
		    }
	    }
	    swap(arr[i_start], arr[minIndex]); // std::swap
    }
}
bool evensFirst(int left, int right)
{
    //if left is even and right is odd, not need to swap
    if ((left % 2 == 0) && (right % 2 != 0))
	    return false;
    //if left is odd and right is even, swap this couple
    if ((left % 2 != 0) && (right % 2 == 0))
	    return true;
    return ascending(left, right);
}
int main()
{
    int arr[] = { 1, 4, 2, 3, 6, 5, 8, 9, 7 };
    int length = sizeof(arr) / sizeof(int);
    cout << "Before sorted: ";
    printArray(arr, length);
    selectionSort(arr, length, evensFirst);
    cout << "After sorted:  ";
    printArray(arr, length);
    return 0;
}

Có đoạn code trên mọi người cho mình hỏi cái đoạn
comparisonFunc(arr[minIndex], arr[i_current]

sẽ trả về giá trị là gì?

với lại trong hàm bool evensFirst sẽ chỉ trả về giá trị true hoặc false hay là trả về một trong 2 giá trị true, false và cả ascending(left, right) ?

đọc tới phần này mình không hiểu lắm, mong mn giúp

Bài liên quan
0