mercredi 22 avril 2015

Learning to implement a C++ BubbleSort using function pointers

My compare function is a simple return true or false. My BubbleSort works by going through the vector once, sorting it once, but not going back to continue to sort. So if the numbers are 1, 5, 2, 4, 3, 6, I will get 5, 1, 4, 2, 6, 3. Instead of 1, 2, 3, 4, 5, 6. If I use my bool swapped, there is an error. Here is the code:

void bSort(vector<int> &vector1, bool (*compare) (int a, int b))
{
    bool swapped = true; //using swapped in following code causes crash
    while(swapped)
    {
        swapped = false;
            for (int i = 0; i < vector1.size(); ++i)
            {
                for (int j = 1; j < vector1.size(); ++j)
                {
                    if ((*compare)(vector1[i], vector1[j]) == true)
                    {
                        swap(vector1[i], vector1[j]);
                        swapped = true;
                    }
                }
            }
    }
}

I have seen a function like this before, and now I am trying to implement it because I want to learn. Please help.

EDIT: Here is the fixed and working function! :)

void bSort(vector<int> &vector1, bool (*compare) (int a, int b))
    {
        bool swapped = true;
        while(swapped)
        {
            swapped = false;
                for (int i = 0; i < vector1.size(); ++i)
                {
                        if ((*compare)(vector1[i], vector1[i+1]) == true)
                        {
                            swap(vector1[i], vector1[i+1]);
                            swapped = true;
                        }
                }
        }
    }

Aucun commentaire:

Enregistrer un commentaire