3

I am trying to utilize the selection sort algorithm to sort an array of object pointers on an int that is a member variable of each object. The getter function is getVar() and works properly. Obviously, what I have here won't work, as I end up trying to swap an int with an object pointer. I sure I'm missing something along the lines of declaring and using anObject* = temp, but I'm just not grasping it. (I see several somewhat similar questions on this topic, but none are quite like this.) Thank you.

void selectSort(anObject* array[], int size) {
int i;
int minIdx;
int minVal;

for (i = 0; i < (size - 1); i++) {
    minIdx = i;
    minVal = array[i]->getVar();
    for (int index = i + 1; index < size; index++) {
        if (array[index]->getVar() < minVal) {
            minVal = array[index]->getVar();
            minIdx = index;
        }
    }
    array[minIdx] = array[i];
    array[i] = minVal; // invalid conversion from int to *anObject
}

}

1
  • 1
    You should swap the elements at i and minIdx ( using a temp ). Do you have a setValue() member function? Commented Feb 22, 2016 at 0:00

1 Answer 1

1

Here's a fix. You can also use std::swap() if you're in C++.

void selectSort(anObject* array[], int size) {
    int i;
    int minIdx;
    int minVal;
    anObject *temp;

    for (i = 0; i < (size - 1); i++) {
        minIdx = i;
        minVal = array[i]->getVar();
        for (int index = i + 1; index < size; index++) {
            if (array[index]->getVar() < minVal) {
                minVal = array[index]->getVar();
                minIdx = index;
            }
        }
        temp = array[minIdx]
        array[minIdx] = array[i];
        array[i] = temp;
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I got the bubble sort version working, but this one is more efficient!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.