1

Iam trying to make selection sort for array of objects considering i have Data class

I want to sort them depending on the id attribute of the object

class Data
{
public:
    string name;
    int id;
};

    }
int main()
{
    Data m[3];
    m[0].id = 5;
    m[1].id = 4;
    m[2].id = 8;
    selsort(m, 3);
    cout << m[0].id;
};

I cannot understand what is wrong nothing happens to the array ?

2
  • Please see ericlippert.com/2014/03/05/how-to-debug-small-programs. Now is a good time to learn how to debug your own programs. Commented Jun 3, 2020 at 18:59
  • As to the logic of the function ? i mean i debug the program but what about the sorting ? the cout result is 5 Commented Jun 3, 2020 at 19:01

2 Answers 2

1

Change:

if ((mry[min].id < mry[j].id) < 0)

to:

if ((mry[min].id > mry[j].id) )

You are finding the minimum index, so you have to swap if you find an index with a value that is lesser than the current minimum.

A better way to accomplish this is to make your function take in another parameter called a comparator function which tells the function how to compare; that way you can reuse your function if you change to mind and what to sort it by another parameter.

void selsort(Data mry[], int n, std::function<int(Data, Data)> cmp) // mry[] is the object array, n is the 
                                     // number of objects in the array
    {
        int pass, j, min;
        Data temp;
        for (pass = 0; pass <= n - 2; pass++)  // passes
        {
            min = pass;
            for (j = pass + 1; j < n; j++)  // in each pass
                if (cmp(mry[min], mry[j]) > 0)
                    min = j;
            temp = mry[min];
            mry[min] = mry[pass];
            mry[pass] = temp;
        }

    }

And you can define a compare by id function:

int compare_by_id(Data d1, Data d2) 
{
    return d1.id - d2.id;
}

Call your function like this:

selsort(array, size, compare_by_id);

The best part is you can define your own function that can compare the elements as you want and that way your selsort() is versatile.

Sign up to request clarification or add additional context in comments.

Comments

1

It seems there is a typo in the function declaration

void selsort(media mry[], int n)
             ^^^^^

I think you mean

void selsort( Data mry[], int n)
              ^^^^

This if statement

if ((mry[min].id < mry[j].id) < 0)

does not make sense.

You should write

if ( mry[min].id < mry[j].id )

Or if you want to sort in the ascending order then write the condition like

if ( mry[j].id < mry[min].id )

Comments

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.